0
0
Rustprogramming~20 mins

Mutable variables in Rust - Practice Problems & Coding Challenges

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

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

Rust
fn main() {
    let mut x = 5;
    x = x + 3;
    println!("{}", x);
}
ACompilation error
B5
C8
D0
Attempts:
2 left
๐Ÿ’ก Hint

Remember that mut allows the variable to be changed.

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

What error will this Rust code produce?

Rust
fn main() {
    let x = 10;
    x = 20;
    println!("{}", x);
}
APrints 10
BPrints 20
CRuntime error: variable not mutable
DCompilation error: cannot assign twice to immutable variable `x`
Attempts:
2 left
๐Ÿ’ก Hint

Variables are immutable by default 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 mut x = 1;
    let y = &x;
    x = 2;
    println!("{}", y);
}
ACannot assign to `x` because it is borrowed as immutable by `y`
BPrints 2
CPrints 1
DCompilation error: `y` is not initialized
Attempts:
2 left
๐Ÿ’ก Hint

Rust enforces borrowing rules to prevent data races.

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

Choose the correct statement about mutable variables in Rust.

AVariables are immutable by default and must be declared with <code>mut</code> to be changed.
BAll variables are mutable by default unless declared with <code>const</code>.
CMutable variables can be changed even when borrowed immutably.
DDeclaring a variable with <code>let mut</code> disables Rust's ownership rules.
Attempts:
2 left
๐Ÿ’ก Hint

Think about Rust's default variable behavior.

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

Analyze the code and select the output it produces.

Rust
fn main() {
    let mut x = 10;
    {
        let y = &mut x;
        *y += 5;
    }
    println!("{}", x);
}
A10
B15
CCompilation error: cannot borrow `x` as mutable more than once
DRuntime error: mutable borrow out of scope
Attempts:
2 left
๐Ÿ’ก Hint

Mutable references allow changing the value they point to.