Summary - Variables
- Rust course
- Beginner
- Lesson 12/115
- 5 min
Combine let, mut, const and shadowing to build a counter program.
Variables summary
let creates an immutable binding; let mut a mutable one; const a compile-time constant (type required, UPPER_CASE); static a global value with a single address; shadowing a new variable with the same name (its type can change). Rust choosing immutability by default lets you see immediately which values change just by reading the code.
Multiple bindings and tuples
A tuple can be destructured with a single let to define several variables:
let (ad, yas) = ("Ada", 36);
let (mut x, y) = (1, 2);
x += y;
println!("{ad} {yas} {x}"); // Ada 36 3Parts you won't use are skipped with _: let (_, yas) = kisi;.
Practice All together
Define const HEDEF: i32 = 10;. In main, destructure with let (baslangic, adim) = (1, 3);, create let mut deger = baslangic; and do deger += adim; while deger < HEDEF. Print the result.
Starter code
fn main() {
// buraya yaz
}Sample solution
const HEDEF: i32 = 10;
fn main() {
let (baslangic, adim) = (1, 3);
let mut deger = baslangic;
while deger < HEDEF {
deger += adim;
}
println!("{}", deger);
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which compiles?
- let x = 1; let x = "bir"; Correct answer
- let x = 1; x = 2;
- let mut x = 1; x = "bir";
- const X = 1;
Explanation: Shadowing can change the type; the others fail because of immutability, a type mismatch and a missing type, respectively.
2 Destructure
let ____ = (10, 20);
println!("{}", a + b);
let (a, b) = (10, 20);
println!("{}", a + b);
Explanation: The tuple pattern (a, b) binds the two values to separate variables.
3 Group summary
| Term | Meaning |
|---|---|
let |
Immutable |
let mut |
Mutable |
const |
Compile-time constant |
Shadowing |
New variable, same name |