Challenge - 5 Problems
Rust Shadowing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of variable shadowing with different types
What is the output of this Rust code snippet?
Rust
fn main() {
let x = 5;
let x = "hello";
println!("{}", x);
}Attempts:
2 left
๐ก Hint
Think about how Rust allows variable shadowing with different types.
โ Incorrect
In Rust, you can shadow a variable with a new variable of a different type. The second 'x' shadows the first and holds the string "hello". So, printing 'x' outputs "hello".
โ Predict Output
intermediate2:00remaining
Value of variable after shadowing in nested scope
What will be printed by this Rust program?
Rust
fn main() {
let x = 10;
{
let x = x + 5;
println!("{}", x);
}
println!("{}", x);
}Attempts:
2 left
๐ก Hint
Remember that shadowing inside a block does not affect the outer variable.
โ Incorrect
Inside the inner block, 'x' is shadowed and equals 15. Outside, the original 'x' remains 10. So the output is 15 then 10.
๐ง Debug
advanced2:00remaining
Why does this shadowing cause a compile error?
This Rust code does not compile. What is the reason?
Rust
fn main() {
let mut x = 5;
let x = x + 1;
x += 2;
println!("{}", x);
}Attempts:
2 left
๐ก Hint
Check the mutability of the shadowed variable.
โ Incorrect
The original 'x' is mutable, but the shadowed 'x' is immutable by default. Trying to mutate the shadowed 'x' causes a compile error.
๐ง Debug
advanced2:00remaining
Identify the compile error related to shadowing
Which option shows a compile error caused by incorrect variable shadowing in Rust?
Attempts:
2 left
๐ก Hint
Check the mutability of the shadowed variable.
โ Incorrect
Option B declares the original 'x' as mutable, but shadows it immutably with 'let x = x + 1'. Trying to mutate the shadowed 'x' with 'x += 2' causes a compile error.
๐ Application
expert3:00remaining
Predict the final value after multiple shadowings
Consider this Rust code. What is the final value printed?
Rust
fn main() {
let x = 2;
let x = x * 3;
{
let x = x - 1;
let x = x * 2;
println!("Inner: {}", x);
}
println!("Outer: {}", x);
}Attempts:
2 left
๐ก Hint
Track each shadowing step carefully.
โ Incorrect
Initially, x=2. Then shadowed to 6 (2*3). Inside the block, x is shadowed to 5 (6-1), then shadowed again to 10 (5*2). So inner print is 10. Outside the block, x remains 6.