Rust Operators
Rust groups its operators into arithmetic, comparison, and logical families, each with strict rules about the types they accept.
Arithmetic Operators
Rust supports the standard set of arithmetic operators: `+`, `-`, `*`, `/`, and `%` for remainder. Both operands of an arithmetic operator must be the same numeric type -- Rust will not silently convert an `i32` to an `f64` for you.
Arithmetic Basics
fn main() {
let sum = 10 + 4;
let difference = 10 - 4;
let product = 10 * 4;
let quotient = 10 / 4;
let remainder = 10 % 4;
println!("{} {} {} {} {}", sum, difference, product, quotient, remainder);
}Integer Division Truncates
When both operands of `/` are integers, the result is an integer too -- the fractional part is discarded, not rounded. `10 / 4` gives `2`, not `2.5`. If you need a fractional answer, at least one operand must be a floating-point type.
Comparison Operators
Comparison operators -- `==`, `!=`, `<`, `>`, `<=`, `>=` -- compare two values of the same type and always produce a `bool`. There's no implicit truthiness in Rust; you can't compare an integer to a boolean, or use an integer directly where a `bool` is expected.
Comparisons
fn main() {
let a = 7;
let b = 12;
println!("{} == {}: {}", a, b, a == b);
println!("{} < {}: {}", a, b, a < b);
println!("{} != {}: {}", a, b, a != b);
}Logical Operators
The logical operators `&&` (and), `||` (or), and `!` (not) work exclusively on `bool` values. Both `&&` and `||` short-circuit: if the left side of `&&` is `false`, or the left side of `||` is `true`, Rust never evaluates the right side at all.
Logical Operators and Short-Circuiting
fn main() {
let age = 20;
let has_id = true;
let can_enter = age >= 18 && has_id;
let needs_review = age < 18 || !has_id;
println!("Can enter: {}", can_enter);
println!("Needs review: {}", needs_review);
}- Arithmetic operators require matching numeric types on both sides
- Comparison operators always return `bool`, never an integer
- `&&` and `||` short-circuit -- the right side may never run
- Compound assignment operators like `+=`, `-=`, `*=` combine an operator with assignment
Exercise: Rust Operators
Does Rust support the ++ increment operator?