Recall & Review
beginner
What is variable shadowing in Rust?
Variable shadowing in Rust means declaring a new variable with the same name as a previous variable. The new variable temporarily hides the old one within its scope.
Click to reveal answer
intermediate
How does shadowing differ from mutability in Rust?
Shadowing lets you reuse a variable name by creating a new variable, even if the original was immutable. Mutability changes the value of the same variable without creating a new one.
Click to reveal answer
intermediate
What happens if you shadow a variable with a different type?
Rust allows shadowing with a different type. The new variable can have a different type than the original, enabling transformations like converting a string to a number.
Click to reveal answer
beginner
Consider this Rust code:<br><pre>let x = 5;<br>let x = x + 1;<br>let x = x * 2;<br>println!("{}", x);</pre><br>What is the output?The output is 12.<br>Explanation:<br>- First x is 5.<br>- Then shadowed x is 6 (5 + 1).<br>- Then shadowed x is 12 (6 * 2).<br>- Finally, 12 is printed.
Click to reveal answer
beginner
Why is variable shadowing useful in Rust?
Shadowing helps keep code clean by reusing variable names for updated values without needing new names. It also allows changing types safely and avoids mutability when not needed.
Click to reveal answer
What does variable shadowing allow you to do in Rust?
✗ Incorrect
Variable shadowing lets you declare a new variable with the same name, hiding the old one temporarily.
Can you shadow a variable with a different type in Rust?
✗ Incorrect
Rust permits shadowing with a different type, enabling type transformations.
What will this Rust code print?<br>
let a = 3;<br>let a = a * 4;<br>println!("{}", a);✗ Incorrect
The variable a is shadowed and updated to 12 (3 * 4), which is printed.
Which of these is NOT true about shadowing in Rust?
✗ Incorrect
Shadowing does NOT require mutability; it works even with immutable variables.
Why might you prefer shadowing over mutability?
✗ Incorrect
Shadowing lets you update values while keeping variables immutable, which can reduce bugs.
Explain variable shadowing in Rust and give a simple example.
Think about declaring the same variable name twice.
You got /3 concepts.
Describe the benefits of using variable shadowing instead of mutability in Rust.
Why might you want to avoid mutable variables?
You got /3 concepts.