Consider the following Rust code snippet. What will it print?
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
let r3 = &mut s;
r3.push_str(", world");
println!("{}", r3);
}Remember Rust does not allow mutable borrow while immutable borrows are active.
The code tries to create a mutable reference r3 while immutable references r1 and r2 are still in use. Rust's borrowing rules forbid this, so it causes a compile-time error.
Analyze the following Rust code. What is the output?
fn main() {
let mut x = 5;
let r1 = &x;
let r2 = &x;
println!("{} and {}", r1, r2);
let r3 = &mut x;
*r3 += 1;
println!("{}", r3);
}Check when the immutable borrows end before the mutable borrow starts.
The immutable borrows r1 and r2 are still in scope when r3 tries to mutably borrow x. Rust forbids this, causing a compile-time error.
Identify the reason for the compilation error in this Rust code snippet.
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &s;
println!("{}", r2);
r1.push_str(", world");
}Check the order and types of borrows on the variable s.
The mutable borrow r1 is active when the code tries to create an immutable borrow r2. Rust forbids immutable borrow while mutable borrow exists.
Given these Rust code snippets, which one will fail to compile because of borrowing rules?
Look for simultaneous mutable and immutable borrows.
Option A tries to create a mutable borrow r2 while an immutable borrow r1 is still active, which is forbidden by Rust's borrowing rules.
In Rust, how many mutable references to the same variable can exist at the same time without causing a compile error?
Recall Rust's exclusive mutable borrowing rule.
Rust allows only one mutable reference to a variable at a time to prevent data races and ensure safety.
