Skip to content
AgileLogics
5 min read

Operators

Prerequisites: Type conversion

Syntax

let sum = 7 + 3;          // arithmetic: + - * / %
let same = sum == 10;     // comparison: == != < > <= >=
let both = same && true;  // logical: && || !
let mut n = 1;
n += 4;                   // compound assignment: += -= *= /= %=
  • Arithmetic — +, -, *, /, and % (remainder). Dividing two integers gives an integer: the fraction is truncated (17 / 5 is 3). Use floats (17.0 / 5.0) for a decimal result.
  • Powers — Rust has no ** operator. Use methods: 2_i32.pow(10) for integers, 2.0_f64.powf(0.5) for floats.
  • Comparison — ==, !=, <, >, <=, >= produce a bool. Both sides must be the same type.
  • Logical — && (and), || (or), ! (not). They work only on bool and short-circuit: the right side isn't evaluated if the left side already decides the result.
  • Compound assignment — +=, -=, *=, /=, %= on a mut variable.
  • Bitwise — &, |, ^ (xor), ! (not), <<, >> on integers.

Example

fn main() {
    let a = 17;
    let b = 5;
    println!("{} {} {} {} {}", a + b, a - b, a * b, a / b, a % b);
    println!("{}", 17.0 / 5.0);
    println!("{}", 2_i32.pow(10));
    println!("{} {} {}", a > b, a == b, a != b);

    let age = 25;
    let has_ticket = true;
    println!("{}", age >= 18 && has_ticket);
    println!("{}", !has_ticket || age < 18);

    let mut score = 10;
    score += 5;
    score *= 2;
    println!("{score}");

    println!("{} {} {}", 0b1100 & 0b1010, 0b1100 | 0b1010, 1 << 4);
    println!("{}", -17 % 5);
}

Expected output

22 12 85 3 2
3.4
1024
true false true
true
false
30
8 14 16
-2

Note the last line: % keeps the sign of the left operand, so -17 % 5 is -2, not 3.

Common mistakes

  • Using ++ or --. Rust has no increment operators:
error: Rust has no postfix increment operator

Write x += 1 instead.

  • Comparing different types. let a = 10; followed by if a == 10.0 doesn't compile — an integer can't be compared with a float:
error[E0277]: can't compare `{integer}` with `{float}`
  • Expecting a decimal from integer division. 7 / 2 is 3; write 7.0 / 2.0 for 3.5.
  • Using ^ for powers. 2 ^ 3 is bitwise xor (1), not 8.

Practice

A year is a leap year if it's divisible by 4 but not by 100, unless it's also divisible by 400. Store 2024 in a variable, compute a bool with that rule, and print 2024 is a leap year: true.

Show solution
fn main() {
    let year = 2024;
    let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    println!("{year} is a leap year: {is_leap}");
}