Complete the code to iterate over the vector and print each number.
let numbers = vec![1, 2, 3]; for num in numbers.[1]() { println!("{}", num); }
iter() when ownership is needed.iter_mut() when mutation is not required.The into_iter() method consumes the vector and returns an iterator over its elements.
Complete the code to iterate over the vector by reference and print each number.
let numbers = vec![4, 5, 6]; for num in numbers.[1]() { println!("{}", num); }
into_iter() which consumes the vector.iter_mut() when mutation is not needed.The iter() method returns an iterator over references to the elements, so the vector is not consumed.
Fix the error in the code to iterate mutably over the vector and increment each number.
let mut numbers = vec![7, 8, 9]; for num in numbers.[1]() { *num += 1; } println!("{:?}", numbers);
iter() which gives immutable references.into_iter() which consumes the vector.The iter_mut() method returns mutable references, allowing modification of elements.
Fill both blanks to create a dictionary (HashMap) from a vector of words with their lengths, filtering words longer than 3 characters.
use std::collections::HashMap; let words = vec!["rust", "is", "fun", "and", "fast"]; let lengths: HashMap<_, _> = words.into_iter() .filter(|word| word.[1]() > 3) .map(|word| (word, word.[2]())) .collect();
to_string() in filter which returns a String, not a number.clone() instead of len().Use len() to get the length of the word for filtering and mapping.
Fill all three blanks to create a HashMap from a vector of tuples, filtering pairs where the number is greater than 10.
use std::collections::HashMap; let pairs = vec![("a", 5), ("b", 15), ("c", 20)]; let map: HashMap<_, _> = pairs.into_iter() .filter(|(_, num)| *num [1] 10) .map(|(key, value)| (key.[2]().[3](), value)) .collect::<HashMap<_, _>>(); println!("{:?}", map);
< instead of > in filter.to_string().Filter numbers greater than 10 using >. Use clone() to copy the key, then to_string() to convert it to a String.
