Rust Operators
An operator is a symbol that does something with values: + adds them, > compares them, && combines two conditions. You have already met several. This page gathers them in one place, so you can come back to it whenever you need a reminder.
Arithmetic and assignment
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * / | add, subtract, multiply, divide | 7 * 6 | 42 |
% | remainder | 20 % 6 | 2 |
+= -= *= /= | change a mut variable | x += 3 | x grows by 3 |
Rust has no ++ or -- like some other languages. To add one, you simply write count += 1.
fn main() {
let mut coins = 10;
coins += 5;
coins -= 3;
coins *= 2;
println!("Coins: {}", coins);
}Coins: 24
Comparison
Comparison operators ask a question and answer with a bool, either true or false.
| Operator | Question |
|---|---|
== | are they equal? |
!= | are they different? |
< > | smaller? bigger? |
<= >= | smaller or equal? bigger or equal? |
Notice the double equals sign. A single = gives a value to a variable; == asks whether two values are the same. Mixing them up is a classic, and the compiler will usually catch it for you.
Logic
Logical operators combine true and false values:
&&means and: true only when both sides are true.||means or: true when at least one side is true.!means not: it flips true to false and false to true.
fn main() {
let age = 16;
let has_ticket = true;
let is_member = false;
println!("Can enter: {}", age >= 12 && has_ticket);
println!("Gets discount: {}", age < 18 || is_member);
println!("Needs to pay full price: {}", !(age < 18 || is_member));
}Can enter: true Gets discount: true Needs to pay full price: false
Which operator goes first?
Just like in school maths, multiplication and division happen before addition and subtraction, and comparisons come after the arithmetic. When in doubt, add round brackets. They cost nothing and make your intention clear to everyone, including future you.
fn main() {
println!("{}", 2 + 3 * 4);
println!("{}", (2 + 3) * 4);
println!("{}", 10 - 4 > 5);
}14 20 true
Practice exercises
- Start a mutable variable at 100, subtract 15, then double it, using the shortcut operators.
- Check whether a number is between 10 and 20 (both included) with
&&. - Predict the result of
8 + 2 * 5 - 3, then run it to check.