Complete the code to declare a mutable String variable.
let [1] = String::from("hello");
mut when you want to change the variable later.let mut without a variable name.In Rust, to make a variable mutable, you add mut before the variable name. So let mut s declares a mutable variable s.
Complete the code to transfer ownership of the String to the function.
fn take_ownership(s: String) {
println!("{}", s);
}
fn main() {
let s1 = String::from("hello");
[1](s1);
}clone instead of calling the function.The function take_ownership takes ownership of the String. Calling take_ownership(s1) moves ownership from s1 to the function.
Fix the error by completing the code to borrow the String instead of moving ownership.
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let s1 = String::from("hello");
let len = calculate_length([1]);
println!("Length: {}", len);
}s1 directly, which moves ownership.*s1 which tries to dereference a value.To borrow a String without taking ownership, you pass a reference using &. So &s1 borrows s1 for the function.
Fill both blanks to create a mutable reference and modify the String.
fn change(s: [1] String) { s.push_str(" world"); } fn main() { let mut s = String::from("hello"); change([2] s); println!("{}", s); }
& when trying to modify.To modify a String through a reference, you need a mutable reference. So the function parameter is &mut String and you pass &mut s when calling.
Fill all three blanks to create a dictionary comprehension that filters words by length.
fn main() {
let words = vec!["apple", "bat", "car", "dog"];
let lengths = [1]: [2] for word in words.iter() if word.len() [3] 3;
println!("{:?}", lengths);
}This Rust code uses an iterator and a filter to create a map of words and their lengths where the length is greater than 3. The blanks fill the key, value, and condition respectively.
