Consider the following Rust code. What will be printed when it runs?
fn take_ownership(s: String) { println!("Inside function: {}", s); } fn main() { let s = String::from("hello"); take_ownership(s); // println!("Outside function: {}", s); // What happens if uncommented? }
Think about what happens to ownership of s when passed to the function.
When s is passed to take_ownership, ownership moves into the function. After the function ends, s is dropped. Trying to use s outside causes a compile error, so the commented line would not compile. The program prints only inside the function.
Look at this Rust code. What will it print?
fn borrow_string(s: &String) { println!("Inside function: {}", s); } fn main() { let s = String::from("world"); borrow_string(&s); println!("Outside function: {}", s); }
Consider how borrowing works in Rust and whether ownership moves.
The function borrows s immutably, so ownership is not moved. The variable s remains valid after the function call, so both prints work.
Examine the code below. What error will the Rust compiler report?
fn main() {
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s1);
}Think about what happens when you assign s1 to s2.
Assigning s1 to s2 moves ownership. After that, s1 is invalid. Using s1 causes a 'use of moved value' error.
Choose the correct Rust function signature that takes ownership of a Vec and returns its length as usize.
Focus on ownership transfer and return type.
Option D takes ownership of the vector and returns its length. Options A and B borrow the vector, not take ownership. Option D takes ownership but returns nothing (unit type), so it does not return the length.
Analyze the following Rust code. What is the value of result after main runs?
fn consume_and_return(s: String) -> String { let mut new_s = s; new_s.push_str(" world"); new_s } fn main() { let s1 = String::from("hello"); let result = consume_and_return(s1); // println!("{}", s1); // Would cause error }
Consider how ownership moves and what the function returns.
The function takes ownership of s, appends " world", and returns the new string. The returned string is assigned to result. The original s1 is moved and cannot be used after.
