Complete the code to borrow a reference to the string without taking ownership.
fn main() {
let s = String::from("hello");
let len = calculate_length([1]);
println!("Length: {}", len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}Using &s borrows a reference to s without taking ownership, allowing calculate_length to read the string.
Complete the code to borrow a mutable reference and modify the string.
fn main() {
let mut s = String::from("hello");
change([1]);
println!("{}", s);
}
fn change(s: &mut String) {
s.push_str(", world");
}Using &mut s borrows a mutable reference, allowing the function to modify the string.
Fix the error by borrowing the string slice correctly.
fn main() {
let s = String::from("hello");
let first_word = first_word([1]);
println!("First word: {}", first_word);
}
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}Borrowing &s passes a string slice reference, matching the function parameter type &str.
Fill in the blank to create a HashMap that maps words to their lengths only if length is greater than 3.
fn main() {
let words = vec!["apple", "cat", "banana", "dog"];
let lengths: std::collections::HashMap<_, _> = words.iter()
.filter(|&&word| word.len() [1] 3)
.map(|&word| (word, word.len()))
.collect();
println!("{:?}", lengths);
}The filter condition word.len() > 3 selects words longer than 3 characters.
Fill all three blanks to create a mutable reference, modify the string, and print the updated value.
fn main() {
let mut s = String::from("hello");
let r = [1] s;
r.push_str([2]);
println!("{}", [3]);
}Use &mut to borrow a mutable reference, append the string ", world", and print the original string s.
