Rust•Operators
Rust Operators: Arithmetic, Comparison, and Checked Math
Learn Rust operators, strict type-matching in expressions, and checked arithmetic.
Syntax
let sum = a + b;
let bitwise = flags << 2;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| +, -, *, / | Arithmetic | Requires operands of identical types. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
fn main() {
let a: i32 = 25;
let b: i32 = 4;
println!("Addition: {} + {} = {}", a, b, a + b);
println!("Integer Div: {} / {} = {}", a, b, a / b);
println!("Float Div: {:.2}", a as f64 / b as f64);
println!("Remainder: {} % {} = {}", a, b, a % b);
// Bitwise shift
let bit_shift = 1 << 3;
println!("1 << 3 = {}", bit_shift);
}Expected Output:
Addition: 25 + 4 = 29 Integer Div: 25 / 4 = 6 Float Div: 6.25 Remainder: 25 % 4 = 1 1 << 3 = 8
How It Works: Step-by-Step
- Lines 5-8: Shows integer division truncation and explicit f64 casting with as.
- Line 11: Bitwise left shift computes 2^3 = 8.
Key Concepts
- Rust panics in debug builds if integer arithmetic overflows.
- Operands must have identical types; no implicit promotions occur.
Common Mistake: Operating on mismatched integer types like i32 + i64
Rust requires explicit type casting with as for all mixed-type expressions.
❌ Incorrect
let a: i32 = 5; let b: i64 = 10; let c = a + b; // Compile Error!
✅ Correct
let c = a as i64 + b;
Related Rust Tutorials & Compiler
Rust Default Immutability, the mut Modifier, and Shadowing
Master Rust variable binding model: default immutability, explicit mut modifier, variable shadowing, and compile-time thread safety.
Rust Type Casting: The as Keyword and Parse Methods
Convert primitive types safely with the as keyword and parse strings with .parse().
Rust Exhaustive Match Pattern Matching and Expression Control Flow
Master expression-driven pattern matching in Rust using exhaustive match blocks, match guards, range patterns (..=), and wildcards (_).
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.