Consider the following Rust code snippet. What will it print?
fn main() {
let x = 10;
let y = &x;
let z = *y + 5;
println!("{}", z);
}Remember that &x creates a reference and *y dereferences it.
The variable y is a reference to x. Dereferencing y gives the value 10, then adding 5 results in 15.
Analyze the following Rust code and determine its output.
fn main() {
let mut a = 5;
{
let b = &mut a;
*b += 10;
}
println!("{}", a);
}Mutable references allow changing the original value.
The mutable reference b adds 10 to a. So a becomes 15.
Examine the code below. What error will the Rust compiler produce?
fn main() {
let mut x = 5;
let y = &x;
let z = &mut x;
*z += 1;
println!("{} {}", y, z);
}Rust does not allow mutable and immutable references to coexist.
The code tries to create an immutable reference y and a mutable reference z to x at the same time, which Rust forbids.
Given the following Rust code, how many references to data are valid at the same time?
fn main() {
let mut data = 100;
let r1 = &data;
let r2 = &data;
println!("{} {}", r1, r2);
let r3 = &mut data;
*r3 += 1;
println!("{}", r3);
}Rust allows multiple immutable references but only one mutable reference at a time.
The code first has two immutable references r1 and r2 valid together. After they are used, a mutable reference r3 is created. Immutable and mutable references cannot coexist.
Analyze the output of this Rust program involving nested references and dereferencing.
fn main() {
let x = 42;
let r1 = &x;
let r2 = &r1;
let r3 = &&r2;
println!("{} {} {}", *r1, **r2, ***r3);
}Each level of dereferencing unwraps one layer of reference.
r1 is a reference to x. r2 is a reference to r1, so **r2 dereferences twice to get x. r3 is a reference to r2, so ***r3 dereferences three times to get x.
