Consider the following Rust code snippet. What will it print?
fn main() {
let x = 5;
// x = 10; // This line is commented out
println!("{}", x);
}Remember that variables declared with let are immutable by default in Rust.
The variable x is immutable and initialized to 5. The commented line does not run, so x remains 5. The program prints 5.
What error will this Rust code produce when compiled?
fn main() {
let y = 3;
y = 4;
println!("{}", y);
}Try to assign a new value to an immutable variable in Rust.
Variables declared with let are immutable by default. Assigning a new value to y causes a compile-time error.
Examine the code below. Why does it fail to compile?
fn main() {
let a = 10;
let a = a + 5;
a = 20;
println!("{}", a);
}Think about variable shadowing and immutability in Rust.
The second a shadows the first and is immutable. Trying to assign a = 20 causes a compile error because a is not mutable.
Choose the correct statement about immutable variables in Rust.
Recall how shadowing works in Rust.
Immutable variables cannot be changed after assignment. However, you can declare a new variable with the same name (shadowing) which can have a different value.
Analyze the code and select the output it produces.
fn main() {
let x = 5;
let x = x + 1;
let mut x = x + 1;
x = x + 1;
println!("{}", x);
}Consider how shadowing and mutability interact in this code.
The first x is 5, shadowed by x = 6, then shadowed by mutable x = 7. Then x is incremented to 8 and printed.