Numbers & Math
7 min · Rust
Do math with variables and the basic operators.
Enemy 1 of 5
Rust supports the same basic arithmetic operators you already know: + for addition, - for subtraction, * for multiplication, and / for division. You can use them directly on numbers, or store numbers in variables first and combine the variables — which is exactly what most real programs do, since the numbers usually come from user input, a file, or a calculation earlier in the program rather than being typed as literals.
Just like with strings, you print the result of a calculation by putting {} inside the format string and passing the expression after the comma: println!("{}", price * quantity). Rust computes price * quantity first, then substitutes the resulting number into the {} placeholder.
A gotcha worth knowing early: Rust's default integer type is i32, and dividing two integers with / performs integer division — it truncates (drops) any remainder rather than giving you a decimal. So 7 / 2 gives 3, not 3.5. If you need a fractional result, at least one of the numbers needs to be a floating-point type like f64. This trips up almost everyone the first time they hit it, in Rust as in C, Java, and many other statically-typed languages.
Loading editor...