0
0
Rustprogramming~5 mins

Variable shadowing in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ADeclare a new variable with the same name as an existing one
BChange the value of a mutable variable
CDelete a variable from memory
DCreate a global variable
Can you shadow a variable with a different type in Rust?
AOnly if the variable is mutable
BYes, Rust allows changing the type when shadowing
CNo, the type must stay the same
DOnly inside functions
What will this Rust code print?<br>
let a = 3;<br>let a = a * 4;<br>println!("{}", a);
A3
B7
C12
DError
Which of these is NOT true about shadowing in Rust?
AShadowing hides the previous variable temporarily
BShadowing can change the variable's type
CShadowing creates a new variable
DShadowing requires the variable to be mutable
Why might you prefer shadowing over mutability?
ATo keep variables immutable and avoid bugs
BTo make variables global
CTo delete variables
DTo speed up the program
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.