</>
Skip to content
Rust lessons (10/43)

Rust — Operators

Arithmetic

let a = 10;
let b = 3;

a + b     // 13
a - b     // 7
a * b     // 30
a / b     // 3    ← INTEGER division (truncates) when both are ints!
a % b     // 1    remainder

The / surprise: 10 / 3 gives 3, not 3.33. Floats divide properly only when an operand is a float:

10.0 / 3.0     // 3.3333333333333335

No ** power operator — use methods:

2i32.pow(8);        // 256
10f64.sqrt();

Comparison

5 == 5      // true   (values must be SAME type to even compile)
"abc" < "abd"   // true, lexicographic

Unlike JavaScript there's no == vs === split and no coercion — "5" == 5 is a compile error, not a surprise.

Logical

let logged_in = true;
let is_admin = false;

logged_in && is_admin     // AND
logged_in || is_admin     // OR
!logged_in                // NOT

Short-circuiting works as expected:

// second call skipped if first fails:
if connected() && send_data() { … }

Compound assignment

let mut score = 10;
score += 5;    // 15
score -= 3;    // 12
score *= 2;    // 24
score /= 4;    // 6
score %= 4;    // 2

Note: += requires the variable be mut.

No increment operator

Rust has no ++ or --:

i += 1;    // the idiomatic way

Truthiness does NOT exist

Conditions must be genuine booleans:

let count = 0;

if count { … }              // ❌ error: expected bool, found integer
if count != 0 { … }         // ✓ explicit
if !name.is_empty() { … }   // ✓

Empty string/zero collections are not falsy in Rust — this removes a whole class of subtle bugs other languages breed.

Operator precedence quick reference

highest:  *  /  %
          +  -
          <<  >>
          &  ^  |
          ==  !=  <  >  <=  >=
          &&
lowest:   ||

Parenthesize anything non-trivial — free clarity.

Mini Practice

  1. Predict then verify 17 / 5, -17 / 5, 17 % -5.
  2. Fix if items.len() { … } — explain the compiler message.
  3. Build a login check with && combining three bools.
  4. Use powi/pow for squares and cubes of floats.
  5. Show that "5" == 5 doesn't compile; compare after parsing instead.

Next: booleans → (already written)

Related Topics

Frequently Asked Questions about Operators

What is Operators in Rust?

Operators is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Operators?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Operators.

Why is Operators important in Rust?

Operators is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.