Complete the code to declare a variable that owns a string.
let s = String::[1]("hello");
new which creates an empty String.clone which copies an existing String.The String::from function creates a new String that owns its data.
Complete the code to transfer ownership of a String to a function.
fn takes_ownership(s: String) {
println!("{}", s);
}
let s1 = String::from("hello");
takes_ownership([1]);ref keyword incorrectly.Passing s1 moves ownership to the function, which is what the function expects.
Fix the error in the code by choosing the correct way to return ownership.
fn gives_ownership() -> String {
let s = String::from("hello");
[1]
}
let s1 = gives_ownership();Using return s; explicitly returns ownership of the String.
Fill both blanks to create a function that takes ownership and returns it back.
fn take_and_give_back([1]: String) -> [2] { [1] }
&str instead of String.The function takes ownership of a String named s and returns it back as a String.
Fill all three blanks to create a function that borrows a String without taking ownership.
fn calculate_length([1]: [2]) -> [3] { [1].len() }
The function borrows a String reference &String named s and returns its length as usize.
