Problem overview
The function long_words receives a vector of strings, words, and a number n. It returns a new vector holding only the words that are strictly longer than n characters, in their original order. A word with exactly n characters is left out, and if nothing qualifies the result is an empty vector.
With words = ["apple", "kiwi", "banana", "fig"] and n = 4, the result is ["apple", "banana"]. "kiwi" has exactly 4 letters, which is not more than 4, and "fig" has 3. With ["go", "went", "gone", "went"] and n = 3, the result is ["went", "gone", "went"]: a repeated word is kept every time it appears.
Approach: build a result as you scan
This is the filter pattern. Start with an empty collection, look at each item once, and add the item to the collection when it passes a test. Because the loop visits the words from first to last and each one is added at the end, the order is preserved without any extra work.
Step by step
- Create the empty result. It is a
Vec<String>declared withlet mut, since words will be pushed into it. - Loop over the words. The loop goes over
wordsitself, not over a reference to it, so eachStringis moved out of the vector into the variableword. - Test the length.
word.len() > nuses a strict comparison. Writing>=would wrongly keep the words of exactlyncharacters. - Push the word.
result.push(word)adds it at the end of the vector. - Return the result. It is the last expression of the function, so it has no semicolon.
The solution in Rust
impl Solution {
fn long_words(words: Vec<String>, n: usize) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
for word in words {
if word.len() > n {
result.push(word);
}
}
result
}
}
The Rust details worth a closer look:
- Moving the words.
for word in wordsconsumes the vector. EachStringis handed to the loop body, andresult.push(word)moves it again into the result, so no text is copied. After the loop,wordscan't be used any more. Words that fail the test are simply dropped at the end of their iteration. nis ausize.len()returns ausize, and Rust only compares two numbers of the same type, sonhas that type too. It can't be negative, which matches the lesson's rule thatnis 0 or more.len()counts bytes. For the lowercase English letters of this lesson, one byte is one letter. For text with accents,"café".len()is 5 although it has four characters;chars().count()gives 4.- The last expression.
resultwithout a semicolon is the function's return value. Adding a semicolon would turn it into a statement, and the function would no longer return a vector.
Edge cases and common mistakes
- Using
>=. With["apple", "kiwi", "banana", "fig"]andn = 4it would also return "kiwi". - No match.
["hi", "to", "be"]withn = 3returns[], because the empty result is never pushed to. n = 0. Every non-empty word is longer than 0, so all words are returned.- Duplicates. Nothing removes repeated words; each occurrence passes or fails on its own length.
Testing
["apple", "kiwi", "banana", "fig"],n = 4gives["apple", "banana"].["hi", "to", "be"],n = 3gives[].["go", "went", "gone", "went"],n = 3gives["went", "gone", "went"].["go", "to"],n = 0gives["go", "to"].
