Consider the following Rust code snippet. What will it print?
fn main() {
let mut x = 10;
let y = &mut x;
*y += 5;
println!("{}", x);
}Remember that &mut allows you to change the value it points to.
The mutable reference y changes the value of x by adding 5. So x becomes 15.
Choose the correct statement about mutable references in Rust.
Think about Rust's borrowing rules to avoid data races.
Rust allows only one mutable reference at a time to ensure safe mutation without data races.
Analyze the code below. What error will the Rust compiler report?
fn main() {
let mut val = 5;
let r1 = &mut val;
let r2 = &mut val;
*r1 += 1;
*r2 += 1;
println!("{}", val);
}Rust enforces exclusive access for mutable references.
The code tries to create two mutable references to val simultaneously, which Rust forbids.
Choose the correct syntax to create a mutable reference to a mutable variable num.
let mut num = 10; // Which line correctly creates a mutable reference to num?
Mutable reference syntax uses &mut.
To create a mutable reference, you write &mut variable. Option A is correct.
Consider this Rust code that uses mutable references and shadowing. What is the final value of data?
fn main() {
let mut data = 3;
{
let r = &mut data;
*r += 4;
}
let r2 = &mut data;
*r2 *= 2;
println!("{}", data);
}Mutable references in separate scopes do not overlap.
The first mutable reference adds 4 to 3, making 7. Then the second mutable reference doubles 7 to 14.
