Sub topic 1
Declaring Variables with `let`
Prerequisites
This chapter assumes you know basic variables, functions, and loops. You should also be able to run a Rust program with cargo or rustc and read simple compiler errors.
Declaring variables with `let`
A binding associates a name with a value. Rust creates most local bindings with let:
fn main() {
let language = "Rust";
let year: u16 = 2010;
println!("{language} was first released in {year}.");
}Rust usually infers the type from the assigned value. The annotation : u16 explicitly declares that year is a 16-bit unsigned integer. You can also declare a binding before assigning it, as long as Rust can prove that it is assigned before being read:
fn main() {
let total: i32;
total = 2 + 3;
println!("{total}");
}A binding has a scope: the region of code where its name can be used. A local binding normally remains available until the end of its enclosing block.
Why bindings are immutable by default
A binding created with let is immutable. Immutable means the name cannot be assigned a different value after its initial assignment:
fn main() {
let count = 1;
// count = 2; // compile-time error
println!("{count}");
}This default makes data flow easier to track. Once a name has a value, other code cannot silently replace that value. The compiler catches accidental reassignment early.
Immutability applies to the binding, not necessarily to every object reachable through it. Rust has separate types for controlled mutation through shared access, such as Cell; those types are introduced later.
Opting into change with `mut`
Use mut when the same binding must be assigned a new value:
fn main() {
let mut count = 0;
count += 1;
count += 1;
println!("{count}");
}Choose mutability based on the role of the binding. Use an immutable binding when the value should not change. Use mut for state that naturally changes, such as a loop counter or accumulated result. Rust requires this choice to be explicit.
Exercise
What is the difference between let count = 0; and let mut count = 0;?
Show answer
Both create a binding initialized to zero, but only the second permits later assignment to count.