Variables
| let bindings | |
| Mutability is opt-in | |
| Shadowing | |
| const and static |
let bindings
The let keyword creates a binding between a name and a value.
The compiler infers the type from the right side, so small programs rarely need annotations.
fn main() {
let apples = 5;
let name = "Ada";
println!("{} {}", name, apples);
}
cargo run
Ada 5
Mutability is opt-in
Bindings are read only by default and cannot be reassigned.
Add mut after let to allow changes, which keeps mutation visible in the source.
fn main() {
let mut count = 0;
count = count + 1;
println!("{}", count);
}
cargo run
1
Shadowing
A new let with the same name creates a fresh binding and hides the old one.
The type may even change, which is handy when a value passes through several steps.
fn main() {
let score = 10;
let score = score + 5;
println!("{}", score);
}
cargo run
15
const and static
Fixed values shared by the whole program use const or static with an explicit type.
Both live for the full run, while const values are inlined at each use site.
const LIMIT: u32 = 10;
static GREETING: &str = "hi";
fn main() {
println!("{} {}", GREETING, LIMIT);
}
cargo run
hi 10
Next: Numbers
Article author: Arthur Isaev