RUST / CHAPTER 01
Bindings and expressions
BeginnerBuild small computations with explicit mutability and expression results.
By the end of this chapter
- Distinguish mutable and immutable bindings
- Use if as an expression
- Trace integer arithmetic
The idea
Start here with basic arithmetic; prior Rust experience is unnecessary. A let binding is immutable unless declared mut. Its value can still be read many times. Shadowing introduces a new binding, while assignment changes an existing mutable binding. Types may be inferred, but a type annotation makes a boundary clear when several interpretations are possible.
Rust blocks and if expressions can produce values. Their final expression supplies the result when it has no trailing semicolon. Both branches must provide compatible types. Integer division discards the fractional part, so choose an appropriate floating point type before division when fractions matter. Follow the variables and expression results separately instead of assuming every line is an assignment.
fn main() {
let total: i32 = 19;
let groups = total / 4;
let label = if groups >= 4 { "ready" } else { "wait" };
println!("{} {}", groups, label);
}4 ready
The integer quotient is four. The condition is true, so the if expression supplies the string ready.
Try it yourself
Write an if expression that returns the larger of two i32 values.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING