Consider the following Rust code snippet. What will it print?
fn main() {
let x = 5;
{
let x = x + 1;
println!("{}", x);
}
println!("{}", x);
}Remember that inner let shadows the outer variable.
The inner block creates a new x equal to the outer x plus 1, so it prints 6. Outside the block, the original x remains 5.
What error will this Rust code produce when compiled?
fn main() {
{
let y = 10;
}
println!("{}", y);
}Variables declared inside a block are not accessible outside it.
The variable y is declared inside the inner block and is not visible outside. Trying to print it outside causes a 'not found in this scope' error.
Examine the code below. Why does it fail to compile?
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
let r3 = &mut s;
println!("{} {} {}", r1, r2, r3);
}Rust enforces rules about mutable and immutable references coexisting.
You cannot have a mutable reference while immutable references to the same variable exist. Here, `r1` and `r2` are immutable references, so `r3` mutable borrow is invalid.
What will this Rust program print?
fn main() {
let a = 1;
{
let a = 2;
{
let a = 3;
println!("{}", a);
}
println!("{}", a);
}
println!("{}", a);
}Each inner block shadows the variable from the outer block.
The innermost block prints 3, the middle block prints 2, and the outer block prints 1.
After running this Rust code, what is the final value of x printed?
fn main() {
let mut x = 5;
{
let x = &mut x;
*x += 1;
}
println!("{}", x);
}Understand how mutable references and shadowing work together.
The mutable reference x inside the block points to the outer x. Incrementing it changes the original x to 6.