Rust Operators
Operators are signs that do maths or comparisons on values. Rust does not change a whole number into a decimal silently.
Add, subtract, multiply, divide
The maths signs work as you expect. Watch the division: with whole numbers, the fraction is dropped:
println!("{} {} {} {}", 7 + 2, 7 - 2, 7 * 2, 7 / 2);The remainder with %
% gives what is left over after a division:
println!("7 % 2 = {}", 7 % 2);Compare and get true or false
The comparison signs answer with a bool, true or false:
println!("{} {} {}", 7 > 2, 7 == 2, 7 != 2);Change the type with as
Cast both sides to f64 first, and the same division keeps its fraction:
let avg = 7 as f64 / 2 as f64;
println!("avg = {}", avg);The shorthand signs
Each shorthand reads the value, does the maths, and saves the answer back into the same variable:
let mut total = 10;
total += 5;
total *= 2;
println!("total = {}", total);Counting up with +=
Four += lines do the counting here. A loop can repeat the same line, as the Loops lesson shows:
let mut count = 0;
count += 1;
count += 1;
count += 1;
count += 1;
println!("count = {}", count);Example
fn main() {
let a: i32 = 7;
let b: i32 = 2;
println!("{} {} {} {}", a + b, a / b, a % b, a * b);
let avg = (a as f64) / (b as f64);
println!("avg = {}", avg);
}Key points
- Write long numbers with underscores to read them easily: 1_000_000
- Rust never does.
- This feels strict, but it prevents silent rounding mistakes.
In this example, a is 7 and b is 2, both whole numbers. The first println! shows four results. It shows a + b (9). It shows a / b (3, because the fraction is dropped). It shows a % b (1, the remainder). And it shows a * b (14). Then both values are changed to f64 with as. Now the division is decimal division, so avg is 3.5. The lesson: the type decides how / behaves.
Note
Rust has no ++ or --.
To count up by one, write x += 1.
Many languages convert number types for you without asking.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
If a and b are both i32, what is 7 / 2?