Operators
Prerequisites: Type conversion
Syntax
let sum = 7 + 3; // arithmetic: + - * / %
let same = sum == 10; // comparison: == != < > <= >=
let both = same && true; // logical: && || !
let mut n = 1;
n += 4; // compound assignment: += -= *= /= %=
- Arithmetic —
+,-,*,/, and%(remainder). Dividing two integers gives an integer: the fraction is truncated (17 / 5is3). Use floats (17.0 / 5.0) for a decimal result. - Powers — Rust has no
**operator. Use methods:2_i32.pow(10)for integers,2.0_f64.powf(0.5)for floats. - Comparison —
==,!=,<,>,<=,>=produce abool. Both sides must be the same type. - Logical —
&&(and),||(or),!(not). They work only onbooland short-circuit: the right side isn't evaluated if the left side already decides the result. - Compound assignment —
+=,-=,*=,/=,%=on amutvariable. - Bitwise —
&,|,^(xor),!(not),<<,>>on integers.
Example
fn main() {
let a = 17;
let b = 5;
println!("{} {} {} {} {}", a + b, a - b, a * b, a / b, a % b);
println!("{}", 17.0 / 5.0);
println!("{}", 2_i32.pow(10));
println!("{} {} {}", a > b, a == b, a != b);
let age = 25;
let has_ticket = true;
println!("{}", age >= 18 && has_ticket);
println!("{}", !has_ticket || age < 18);
let mut score = 10;
score += 5;
score *= 2;
println!("{score}");
println!("{} {} {}", 0b1100 & 0b1010, 0b1100 | 0b1010, 1 << 4);
println!("{}", -17 % 5);
}
Expected output
22 12 85 3 2
3.4
1024
true false true
true
false
30
8 14 16
-2
Note the last line: % keeps the sign of the left operand, so
-17 % 5 is -2, not 3.
Common mistakes
- Using
++or--. Rust has no increment operators:
error: Rust has no postfix increment operator
Write x += 1 instead.
- Comparing different types.
let a = 10;followed byif a == 10.0doesn't compile — an integer can't be compared with a float:
error[E0277]: can't compare `{integer}` with `{float}`
- Expecting a decimal from integer division.
7 / 2is3; write7.0 / 2.0for3.5. - Using
^for powers.2 ^ 3is bitwise xor (1), not8.
Practice
A year is a leap year if it's divisible by 4 but not by 100, unless
it's also divisible by 400. Store 2024 in a variable, compute a
bool with that rule, and print 2024 is a leap year: true.
Show solution
fn main() {
let year = 2024;
let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
println!("{year} is a leap year: {is_leap}");
}