Consider the following Rust code snippet. What will it print?
fn main() {
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s2);
}Remember that in Rust, moving ownership transfers the value, so the original variable cannot be used after move.
The variable s1 is moved to s2. Using s2 is valid and prints "hello". Using s1 after move would cause a compile error, but here s2 is used.
Analyze the following Rust code. What error will the compiler report?
fn main() {
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
let r3 = &mut s;
println!("{} {} {}", r1, r2, r3);
}Rust enforces that you cannot have mutable and immutable references to the same data at the same time.
The code tries to create two immutable references r1 and r2, then a mutable reference r3 to the same variable s. This causes a compile-time error because mutable and immutable borrows cannot coexist.
What is the ownership problem in the following Rust code?
fn take_ownership(s: String) { println!("{}", s); } fn main() { let s = String::from("hello"); take_ownership(s); println!("{}", s); }
Think about what happens to ownership when a variable is passed to a function by value.
The function take_ownership takes ownership of the String s. After calling the function, s in main is no longer valid, so using it causes a compile error.
Which of the following code snippets correctly borrows a mutable reference to a variable?
Remember that to borrow a mutable reference, the original variable must be declared mutable.
Option D declares x as mutable and borrows a mutable reference y. It then modifies the value through y. Other options either borrow mutable reference from immutable variable or try to modify through immutable reference, causing errors.
Consider this Rust code. How many elements does the vector v2 contain after the ownership transfer?
fn main() {
let v1 = vec![1, 2, 3];
let v2 = v1;
// println!("{}", v1.len()); // This line is commented out
println!("{}", v2.len());
}When ownership moves, the new owner has full access to the data.
The vector v1 is moved to v2. After the move, v2 owns the vector with 3 elements. The commented line would cause a compile error if uncommented.
