0
0
Rustprogramming~20 mins

Scope of variables in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this Rust code with variable shadowing?

Consider the following Rust code snippet. What will it print?

Rust
fn main() {
    let x = 5;
    {
        let x = x + 1;
        println!("{}", x);
    }
    println!("{}", x);
}
A6\n5
B6\n6
C5\n6
D5\n5
Attempts:
2 left
๐Ÿ’ก Hint

Remember that inner let shadows the outer variable.

โ“ Predict Output
intermediate
2:00remaining
What error does this Rust code produce due to variable scope?

What error will this Rust code produce when compiled?

Rust
fn main() {
    {
        let y = 10;
    }
    println!("{}", y);
}
Aerror: cannot find value `y` in this scope
Berror: use of moved value: `y`
Cerror: expected `;` after expression
DNo error, prints 10
Attempts:
2 left
๐Ÿ’ก Hint

Variables declared inside a block are not accessible outside it.

๐Ÿ”ง Debug
advanced
2:30remaining
Why does this Rust code fail to compile due to variable borrowing and scope?

Examine the code below. Why does it fail to compile?

Rust
fn main() {
    let mut s = String::from("hello");
    let r1 = &s;
    let r2 = &s;
    let r3 = &mut s;
    println!("{} {} {}", r1, r2, r3);
}
ACannot borrow `s` as immutable because it is already borrowed as mutable
BNo error, prints: hello hello hello
CCannot print multiple references in one println!
DCannot borrow `s` as mutable because it is also borrowed as immutable
Attempts:
2 left
๐Ÿ’ก Hint

Rust enforces rules about mutable and immutable references coexisting.

โ“ Predict Output
advanced
2:00remaining
What is the output of this Rust code with nested scopes and variable shadowing?

What will this Rust program print?

Rust
fn main() {
    let a = 1;
    {
        let a = 2;
        {
            let a = 3;
            println!("{}", a);
        }
        println!("{}", a);
    }
    println!("{}", a);
}
A3\n3\n3
B1\n2\n3
C3\n2\n1
D1\n1\n1
Attempts:
2 left
๐Ÿ’ก Hint

Each inner block shadows the variable from the outer block.

โ“ Predict Output
expert
3:00remaining
What is the value of `x` after this Rust code runs with shadowing and mutation?

After running this Rust code, what is the final value of x printed?

Rust
fn main() {
    let mut x = 5;
    {
        let x = &mut x;
        *x += 1;
    }
    println!("{}", x);
}
ACompilation error due to borrowing
B6
C7
D5
Attempts:
2 left
๐Ÿ’ก Hint

Understand how mutable references and shadowing work together.