Complete the code to pass ownership of the string to the function.
fn take_ownership(s: String) {
println!("{}", s);
}
fn main() {
let s = String::from("hello");
take_ownership([1]);
}Passing s moves ownership to the function. Using s.clone() copies, &s borrows, and ref s is invalid here.
Complete the code to borrow the string without taking ownership.
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let s1 = String::from("hello");
let len = calculate_length([1]);
println!("Length: {}", len);
}Using &s1 borrows the string, allowing the function to read it without taking ownership.
Fix the error in the function signature to allow mutable borrowing.
fn change(s: [1] String) { s.push_str(", world"); } fn main() { let mut s = String::from("hello"); change(&mut s); println!("{}", s); }
The function must accept a mutable reference &mut String to modify the string without taking ownership.
Fill both blanks to correctly return ownership and length from the function.
fn calculate_length_and_return(s: [1]) -> (String, usize) { let length = s.len(); ([2], length) } fn main() { let s1 = String::from("hello"); let (s2, len) = calculate_length_and_return(s1); println!("{} has length {}", s2, len); }
The function takes ownership of String and returns it back with the length. Returning s gives ownership back.
Fill all three blanks to correctly use mutable references and modify the string.
fn append_world([2] s: [1] String) { s.[3](", world"); } fn main() { let mut s = String::from("hello"); append_world(&mut s); println!("{}", s); }
The function takes a mutable reference &mut String and uses push_str to append text.
