Rust Basics

Rust Operators and Arithmetic

Why is 17 / 5 equal to 3 in Rust? Learn arithmetic, comparison and logical operators.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • + - * / and %
  • Integer division
  • Comparisons with && and ||
Expression → result
17 / 53
17 % 52
17 as f64 / 5 as f643.4
2_i32.pow(10)1024

How Rust evaluates an expression

Operators combine values into expressions. Rust follows the usual math rules, with one thing to remember: dividing two integers drops the fraction.

17 / 5 is 3 because both numbers are integers, and 17 % 5 is the remainder 2. Converting both sides with as f64 keeps the fraction. && is true only when both comparisons are true, and pow raises a number to a power.

Key points

  1. int / int drops the fraction: 17 / 5 is 3.
  2. % gives the remainder: 17 % 5 is 2.
  3. Convert with as f64 to keep the fraction.

Runnable Rust example

Rust
Run code →
main.rs
fn main() {
    let a = 17;
    let b = 5;
    println!("{} {} {}", a + b, a - b, a * b);
    println!("{} {}", a / b, a % b);
    println!("{}", a as f64 / b as f64);
    println!("{}", a > b && b != 0);
    println!("{}", 2_i32.pow(10));
}
Get a Run button for this example Result of running the code
22 12 85
3 2
3.4
true
1024

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges