Sub topic 2
Shadowing versus Mutation
This chapter assumes basic Rust syntax, functions, loops, and familiarity with compiler errors.
Shadowing versus mutation
Mutation changes the value stored in an existing mutable binding. Add mut when reassignment is part of the design.
Shadowing creates a new binding with the same name. The new binding can have a different type, and the earlier binding remains unchanged outside the new binding's scope.
fn main() {
let mut count = 1;
count += 1; // mutation
let value = "42";
let value: u32 = value.parse().expect("valid number"); // shadowing
{
let value = value + 1;
println!("inner value: {value}");
}
println!("count: {count}, outer value: {value}");
}Mutation requires a mutable binding and keeps the same binding and type. Shadowing is useful when a value passes through transformations, such as text becoming a number.
`const` and `static` items
A const is a named compile-time value. It must have an explicit type and can be inlined wherever it is used. A static is one value stored at a fixed memory location for the program's lifetime.
const MAX_RETRIES: u8 = 3;
static APP_NAME: &str = "worker";
fn main() {
println!("{APP_NAME}: {MAX_RETRIES}");
}Use const for fixed values. Use static when a program-wide item needs stable identity or storage. Shared mutable statics require unsafe and careful synchronization.
Type inference and explicit annotations
Rust infers a binding's type from its value and how the value is used. Add an annotation when inference is ambiguous, when an API needs a specific type, or when documenting an important boundary.
fn main() {
let count = 10; // inferred as i32
let size: usize = 4; // explicit type
let ratio: f64 = 0.5;
println!("{count} {size} {ratio}");
}Integer types and literals
Rust's signed integers range from i8 to i128; unsigned integers range from u8 to u128. isize and usize match the target platform's pointer size. An unsuffixed integer literal usually defaults to i32.
| Type | Meaning | Example |
|---|---|---|
| `u8` | Unsigned 8-bit integer | `255u8` |
| `i64` | Signed 64-bit integer | `-20i64` |
| `usize` | Pointer-sized unsigned integer | `index: usize` |
Choose a type based on the data and API. Do not use a narrow type only to save memory without measuring the effect.
Exercise
What is the key difference between let mut x = 1; x = 2; and let x = 1; let x = 2;?
Show answer
The first mutates one mutable binding. The second shadows the first binding by creating a new immutable binding.