Rust Operators
Operators are the symbols you use to do math, compare values, and combine conditions. Most of these will look familiar if you’ve used any C-like language.
Arithmetic operators
Section titled “Arithmetic operators”fn main() { let a = 10; let b = 3;
println!("{}", a + b); // 13 println!("{}", a - b); // 7 println!("{}", a * b); // 30 println!("{}", a / b); // 3 (integer division, drops the remainder) println!("{}", a % b); // 1 (remainder)}Comparison operators
Section titled “Comparison operators”These compare two values and give back a bool:
fn main() { let a = 5; let b = 8;
println!("{}", a == b); // false println!("{}", a != b); // true println!("{}", a < b); // true println!("{}", a > b); // false println!("{}", a <= b); // true println!("{}", a >= b); // false}You’ll use these constantly inside if conditions, which we cover on the If…Else page.
Logical operators
Section titled “Logical operators”Logical operators combine or invert boolean values:
fn main() { let is_logged_in = true; let is_admin = false;
println!("{}", is_logged_in && is_admin); // false — both must be true println!("{}", is_logged_in || is_admin); // true — at least one is true println!("{}", !is_admin); // true — flips false to true}&&— and: true only if both sides are true.||— or: true if at least one side is true.!— not: flips true to false and vice versa.
Assignment operators
Section titled “Assignment operators”Beyond the plain =, Rust has shorthand operators that update a variable based on its current value:
fn main() { let mut score = 10;
score += 5; // same as: score = score + 5 score -= 2; // score = score - 2 score *= 3; // score = score * 3 score /= 2; // score = score / 2
println!("{score}");}Remember the variable needs mut for any of these to compile — you’re changing its value.
- Arithmetic:
+ - * / %. Integer division truncates — no decimals. - Comparison:
== != < > <= >=, all return abool. - Logical:
&&(and),||(or),!(not). - Assignment shorthand:
+= -= *= /=update amutvariable in place.