0
0
Rustprogramming~20 mins

Variable shadowing in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust Shadowing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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);
}
A"hello"
B5
CCompilation error due to type mismatch
DRuntime error
Attempts:
2 left
๐Ÿ’ก Hint
Think about how Rust allows variable shadowing with different types.
โ“ Predict Output
intermediate
2: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);
}
A10\n10
B10\n15
C15\n15
D15\n10
Attempts:
2 left
๐Ÿ’ก Hint
Remember that shadowing inside a block does not affect the outer variable.
๐Ÿ”ง Debug
advanced
2: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);
}
ACannot mutate 'x' because it is shadowed as immutable
BCannot add integer to a mutable variable
CShadowing is not allowed with mutable variables
DMissing semicolon after 'let x = x + 1'
Attempts:
2 left
๐Ÿ’ก Hint
Check the mutability of the shadowed variable.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify the compile error related to shadowing
Which option shows a compile error caused by incorrect variable shadowing in Rust?
Alet x = 5; let x = x + 1;
Blet mut x = 5; let x = x + 1; x += 2;
Clet x = 5; let x: i32 = x + 1;
Dlet x = 5; let mut x = x + 1; x += 2;
Attempts:
2 left
๐Ÿ’ก Hint
Check the mutability of the shadowed variable.
๐Ÿš€ Application
expert
3: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);
}
AInner: 10\nOuter: 5
BInner: 4\nOuter: 6
CInner: 10\nOuter: 6
DInner: 4\nOuter: 5
Attempts:
2 left
๐Ÿ’ก Hint
Track each shadowing step carefully.