0
0
Rustprogramming~20 mins

Immutable variables in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust Immutable 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 immutable variables?

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

Rust
fn main() {
    let x = 5;
    // x = 10; // This line is commented out
    println!("{}", x);
}
ACompilation error: cannot assign twice to immutable variable `x`
B10
C5
D0
Attempts:
2 left
๐Ÿ’ก Hint

Remember that variables declared with let are immutable by default in Rust.

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

What error will this Rust code produce when compiled?

Rust
fn main() {
    let y = 3;
    y = 4;
    println!("{}", y);
}
ACompilation error: cannot assign twice to immutable variable `y`
BPrints 4
CRuntime error: cannot assign to immutable variable
DPrints 3
Attempts:
2 left
๐Ÿ’ก Hint

Try to assign a new value to an immutable variable in Rust.

๐Ÿ”ง Debug
advanced
2:30remaining
Why does this Rust code fail to compile?

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

Rust
fn main() {
    let a = 10;
    let a = a + 5;
    a = 20;
    println!("{}", a);
}
ABecause the second <code>a</code> shadows the first and is immutable, so <code>a = 20</code> is invalid
BBecause Rust does not allow variable shadowing
CBecause <code>a</code> is mutable but not initialized
DBecause <code>a</code> is declared twice with the same value
Attempts:
2 left
๐Ÿ’ก Hint

Think about variable shadowing and immutability in Rust.

๐Ÿง  Conceptual
advanced
2:00remaining
Which statement about Rust immutable variables is true?

Choose the correct statement about immutable variables in Rust.

AImmutable variables can be changed anytime without any special syntax.
BImmutable variables can be reassigned only if declared with <code>mut</code> keyword.
CImmutable variables are automatically mutable if used inside functions.
DImmutable variables cannot be changed after assignment unless shadowed by a new variable with the same name.
Attempts:
2 left
๐Ÿ’ก Hint

Recall how shadowing works in Rust.

โ“ Predict Output
expert
3:00remaining
What is the output of this Rust code involving immutable and mutable variables?

Analyze the code and select the output it produces.

Rust
fn main() {
    let x = 5;
    let x = x + 1;
    let mut x = x + 1;
    x = x + 1;
    println!("{}", x);
}
A7
B8
CCompilation error due to reassignment of immutable variable
D6
Attempts:
2 left
๐Ÿ’ก Hint

Consider how shadowing and mutability interact in this code.