Consider the following Rust code snippet. What will it print?
fn main() {
let mut x = 5;
x = x + 3;
println!("{}", x);
}Remember that mut allows the variable to be changed.
The variable x is declared mutable with mut. It starts at 5, then 3 is added, so the output is 8.
What error will this Rust code produce?
fn main() {
let x = 10;
x = 20;
println!("{}", x);
}Variables are immutable by default in Rust.
The variable x is not declared mutable, so assigning a new value causes a compile-time error.
Examine the code below. Why does it fail to compile?
fn main() {
let mut x = 1;
let y = &x;
x = 2;
println!("{}", y);
}Rust enforces borrowing rules to prevent data races.
The variable x is borrowed immutably by y. You cannot mutate x while an immutable borrow exists.
Choose the correct statement about mutable variables in Rust.
Think about Rust's default variable behavior.
Rust variables are immutable by default. You must use mut to allow changes. Ownership and borrowing rules still apply.
Analyze the code and select the output it produces.
fn main() {
let mut x = 10;
{
let y = &mut x;
*y += 5;
}
println!("{}", x);
}Mutable references allow changing the value they point to.
The mutable reference y changes x by adding 5. After the inner scope ends, x is 15.