Consider the following Rust code snippet. What will it print?
fn main() {
let x = 10;
let y = &x;
let z = &x;
println!("{} {}", y, z);
}Remember, Rust allows multiple immutable references at the same time.
Rust permits multiple immutable references simultaneously because they do not allow mutation. So both y and z point to x safely, printing its value twice.
Analyze the following Rust code. What error will the compiler show?
fn main() {
let mut x = 5;
let y = &x;
let z = &mut x;
println!("{} {}", y, z);
}Rust does not allow mutable and immutable references to the same variable at the same time.
The compiler forbids having a mutable reference while immutable references exist. Here, y is an immutable reference and z tries to be mutable simultaneously, causing a compile-time error.
Look at this Rust code snippet. It fails to compile. What is the cause?
fn main() {
let s = String::from("hello");
let r1 = &s;
let r2 = &mut s;
println!("{} and {}", r1, r2);
}Check Rust's borrowing rules about mutable and immutable references.
Rust forbids mutable and immutable references to the same variable at the same time. Here, r1 is an immutable reference and r2 tries to be mutable simultaneously, causing a compile-time error.
What will this Rust program print?
fn main() {
let x = 42;
let r1 = &x;
let r2 = &r1;
println!("{}", **r2);
}Think about how many layers of references you have and how to access the original value.
r1 is a reference to x, and r2 is a reference to r1. Using **r2 dereferences twice to get the original value 42.
Examine the following Rust code. What will it print?
fn main() {
let x = 5;
let x = &x;
let x = &x;
println!("{}", ***x);
}Consider how shadowing creates multiple layers of references and how many times you need to dereference.
Each let x = &x; creates a new reference to the previous x. The final ***x dereferences three times to get the original value 5.
