1 · Values and control flow · 25 MIN
Bindings, expressions and functions
Rust distinguishes mutable bindings from immutable ones.
let creates an immutable binding unless mut is requested. A function’s final expression can be its returned value without a return keyword. Adding a semicolon changes that expression into a statement, which can make the function return the unit type instead of the declared integer. The example keeps calculation separate from println. Fixed-width integers have explicit ranges, and overflow behavior varies by build settings; use checked arithmetic when overflow is part of your input contract.
Read the compiler’s expected and found types before changing code.
Read the example
fn total(price: i32, quantity: i32) -> i32 { price * quantity }
fn main() {
let price = 12;
let mut quantity = 2;
quantity += 1;
println!("{}", total(price, quantity));
println!("{}", total(price, 0));
}Check the expected output
36 0
Your challenge
Add a function returning a discounted total while rejecting negative inputs with Option.
Solution cost: O(1) fixed-width arithmetic. time · O(1) auxiliary state. space
Common trap
A trailing semicolon on the last expression can remove the intended return value.
Study the project implementation
fn total(price: i32, quantity: i32) -> i32 { price * quantity }
fn main() {
let price = 12;
let mut quantity = 2;
quantity += 1;
println!("{}", total(price, quantity));
println!("{}", total(price, 0));
}Further reading: Official documentation
Next lesson: Borrow strings instead of moving them →