Shadowing
- Rust course
- Beginner
- Lesson 11/115
- 4 min
Reuse a name by shadowing the previous binding.
Shadowing
Writing a new let with the same name shadows the previous variable. This is different from mut: a new variable is created and even its type can change:
let girdi = "42"; // &str
let girdi: i32 = girdi.parse().unwrap(); // i32
let girdi = girdi * 2; // 84
println!("{girdi}");It lets you keep the same name through conversion steps without inventing names like girdi_str, girdi_sayi.
Scope and shadowing
Shadowing done in an inner block is valid only inside that block; when the block ends, the outer value returns:
let x = 5;
{
let x = x * 2;
println!("iç: {x}"); // 10
}
println!("dış: {x}"); // 5Practice Shadowing chain
Start with let deger = " 21 ";. First write let deger = deger.trim();, then let deger: i32 = deger.parse().unwrap();, finally let deger = deger * 2;, and print the result.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let deger = " 21 ";
let deger = deger.trim();
let deger: i32 = deger.parse().unwrap();
let deger = deger * 2;
println!("{}", deger);
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the key difference between shadowing and <code>mut</code>?
- Shadowing only works with constants
- Shadowing creates a new variable and can change the type Correct answer
- mut can change the type
- They are the same
Explanation: mut changes the value of the same variable; shadowing with let creates a brand-new binding and the old value becomes unreachable.
2 Shadow it
let ad = " Ada ";
____ ad = ad.trim();
let ad = " Ada ";
let ad = ad.trim();
Explanation: Writing let again creates a new variable with the same name.
3 Code and result
| Term | Meaning |
|---|---|
let x = 5; let x = x + 1; |
x = 6 (new variable) |
let x = "1"; let x: i32 = ... |
Type changed |
let x in an inner block |
Only in the block |
mut x = "a" (x i32) |
Compile error |