Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 132 ยท Operators and Control Flow

Operators

Learn all Rust operators - arithmetic, comparison, short-circuit logic, bitwise and shifts, compound assignment, why there is no ++, precedence, ranges and how operators map to traits.

Operators are the symbols you use to combine values: +, ==, &&, <<, .. and friends. Rust's operators will look familiar if you know C, Java or Python, but a few details are different and are worth learning on purpose: arithmetic never mixes types silently, there is no ++ or --, && and || only accept bool, and every operator is really a method of a trait, which is why you can overload them for your own types.

This lesson walks through each group of operators with runnable code, gives you the precedence table, and previews operator overloading. It assumes you know the scalar types and the basics of variables. Overflow behavior gets its own treatment in the overflow lesson.

Arithmetic operators

There are five: + (add), - (subtract), * (multiply), / (divide) and % (remainder).

Rust Arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two rules matter:

  • Both operands must have the same type. There is no implicit widening. 4_i32 * 0.25_f64 is an error, and you write 4 as f64 * 0.25 (type conversion explains casts).
  • Integer / truncates toward zero, so -7 / 2 is -3, and % keeps the sign of the left side: -7 % 3 is -1. For a result that is always non-negative, use rem_euclid.

Dividing an integer by zero panics at runtime. Dividing a float by zero gives infinity or NaN and never panics.

Rust Mixed types do not add up (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports error[E0277]: cannot multiply `i32` by `f64` , with the help the trait `Mul<f64>` is not implemented for `i32` . It is telling you how operators really work: * calls Mul::mul, and no implementation of Mul<f64> exists for i32. The fix is a cast on one side: count as f64 * price.

Comparison operators

==, !=, <, >, <= and >= compare two values of the same type and produce a bool. They work on numbers, chars, strings, tuples, arrays and any type that implements PartialEq or PartialOrd.

Rust Comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The last two lines show why floating-point types are only PartialEq and PartialOrd, not Eq and Ord: NaN ("not a number") is not equal to anything, not even itself, and is neither smaller nor greater than any number.

Unlike in C, comparisons do not chain. 1 < x < 10 is a compile error (comparison operators cannot be chained); write 1 < x && x < 10, or use a range: (2..10).contains(&x).

Logical operators

&& (and), || (or) and ! (not) work on bool only. Numbers are never "truthy" or "falsy" in Rust, so if count { ... } does not compile (error[E0308]: mismatched types, expected bool, found integer).

&& and || are short-circuiting: the right operand is evaluated only if the left one has not already decided the result.

Rust Short-circuit evaluation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Short-circuiting is more than an optimization: divisor != 0 && 100 / divisor > 5 is safe precisely because the division never runs when the divisor is zero. The single-character & and | also work on bool, but they always evaluate both sides. You rarely want that.

Bitwise operators and shifts

For integers, Rust has & (and), | (or), ^ (xor), ! (not, flips every bit) and the shifts << and >>. They treat the number as a row of bits.

Rust Bitwise operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Facts to know:

  • ! means logical NOT on bool and bitwise NOT on integers. Rust has no separate ~ operator.
  • << on an unsigned type shifts bits out the left end without complaint (they are lost); that is not treated as overflow. Shifting by the number of bits or more is an error: in a debug build 1u8 << 8 panics with attempt to shift left with overflow.
  • >> on a signed type is an arithmetic shift that keeps the sign; on an unsigned type it fills with zeros.
  • Shifting left by one multiplies by two as long as no bits fall off, but write * 2 when you mean arithmetic. The optimizer already knows the trick.

The bit-flag pattern in the middle, |= 1 << n, &= !(1 << n), ^= 1 << n, is worth memorizing.

Compound assignment and the missing ++

Every binary arithmetic and bitwise operator has an assignment form: +=, -=, *=, /=, %=, &=, |=, ^=, <<= and >>=. x += 1 means "add one to x in place" and requires x to be declared mut.

Rust Compound assignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust has no ++ and -- operators. This is deliberate: i++ and ++i mix a read and a write in one expression, which is a classic source of confusing code. Use i += 1 and i -= 1. Also, an assignment such as x = 5 is an expression of type (), so a = b = 0 does not do what it does in C (it is a type error), and if x = 5 { } cannot be written by accident.

Precedence and associativity

When an expression contains several operators, precedence decides the grouping. From highest (binds tightest) to lowest:

Level Operators Associativity
1 method calls ., field access, ?, indexing [], calls () left to right
2 unary - * (deref) ! & &mut right to left
3 as left to right
4 * / % left to right
5 + - left to right
6 << >> left to right
7 & left to right
8 ^ left to right
9 | left to right
10 == != < > <= >= not chainable
11 && left to right
12 || left to right
13 .. ..= not chainable
14 = += -= ... right to left
15 return break closures n/a
Rust Precedence in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Some of these results are surprising: 2 + 3 << 1 is 10 (not 8), because arithmetic binds tighter than shifts, and -2_i32.pow(2) is -4, not 4. Unlike C, bitwise &, | and ^ bind tighter than comparisons, so flags & 4 == 4 means (flags & 4) == 4, which is what you wanted. Still, when an expression mixes bit operators with anything else, add parentheses. Clear code beats clever code, and rustfmt keeps your parentheses.

Range operators

.. and ..= build ranges. a..b includes a and excludes b; a..=b includes both. Ranges are values of ordinary types (Range<T>, RangeInclusive<T>) that you can store, loop over, slice with and test with contains.

Rust Ranges are values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Either end can be left open (..5, 3.., ..). Ranges drive for loops (loops), slicing (slices) and patterns in match.

Operators are traits

Every operator on a non-primitive type is a call to a trait method. a + b is Add::add(a, b), a == b is PartialEq::eq(&a, &b), -a is Neg::neg(a), a[i] is Index::index(&a, i), and a += b is AddAssign::add_assign(&mut a, b). They all live in std::ops and std::cmp.

That is why String + &str works, why two Strings cannot be added, and why you can give your own types operators:

Rust A first operator overload

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Defining Add and Mul for Vec2 made + and * work on it. Traits explains the impl Trait for Type syntax, and the operator overloading lesson covers the whole family (including Neg, Index, AddAssign, and implementing for references).

Overload an operator only when its meaning is obvious: + for vectors, money or durations is natural. Using + for something unrelated, such as "add a user to a group", makes code hard to read. Prefer a named method.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does -7 / 2 evaluate to for integers?

    Integer division truncates toward zero, so -7 / 2 is -3. The remainder -7 % 2 is -1.
  2. 2. Which line does not compile?

    Arithmetic operators need both operands to have the same type. There is no implicit conversion from i32 to f64; write 3_i32 as f64 * 2.5.
  3. 3. What is the result of let ok = n != 0 && 100 / n > 5; when n is 0?

    && short-circuits: when the left side is false, the right side is never evaluated, so the division does not run.
  4. 4. How do you increment a mutable variable i by one in Rust?

    Rust has no ++ or -- operators. Use i += 1 (and declare i with mut).
  5. 5. What does a + b mean for a struct that implements std::ops::Add?

    Operators are sugar for trait methods. Implementing Add for your type makes + work with it.

Summary

  • Arithmetic operators need operands of the same type; cast explicitly with as. Integer / truncates toward zero.
  • Comparisons produce bool, do not chain, and need PartialEq/PartialOrd; NaN is not equal to itself.
  • && and || short-circuit and accept only bool; & and | on bool evaluate both sides.
  • Bitwise & | ^ ! and shifts << >> work on integers; shifting by the full width or more panics in debug builds.
  • There is no ++ or --; use += 1. Compound assignment needs mut.
  • Use parentheses when mixing operators, because precedence has surprises such as 2 + 3 << 1 and -2_i32.pow(2).
  • .. and ..= build range values; every operator is a trait method, so you can overload them for your types.

Next: if, else if and else