Complete the code to pass ownership of the string to the function.
fn print_string(s: String) {
println!("{}", s);
}
fn main() {
let my_string = String::from("hello");
print_string([1]);
}Passing my_string moves ownership to the function.
Complete the code to borrow the string without taking ownership.
fn print_string(s: &String) {
println!("{}", s);
}
fn main() {
let my_string = String::from("world");
print_string([1]);
println!("{}", my_string);
}Passing &my_string borrows the string, so ownership stays in main.
Fix the error by completing the code to return ownership back to the caller.
fn take_and_return(s: String) -> String {
println!("{}", s);
[1]
}
fn main() {
let my_string = String::from("rust");
let my_string = take_and_return(my_string);
println!("{}", my_string);
}Returning s moves ownership back to the caller.
Fill both blanks to create a function that borrows a string slice and prints it.
fn print_slice(s: [1]) { println!("{}", s); } fn main() { let my_string = String::from("slice"); print_slice([2]); }
The function takes a string slice &str, and we pass a slice using my_string.as_str().
Fill all three blanks to create a function that takes ownership, modifies, and returns the string.
fn add_exclamation(mut s: [1]) -> [2] { s.push_str([3]); s } fn main() { let my_string = String::from("hello"); let my_string = add_exclamation(my_string); println!("{}", my_string); }
The function takes ownership of a String, appends an exclamation mark, and returns the modified String.
