Problem overview
The function word_lengths receives a vector of strings, words, and returns a vector with the length of each word, in the same order. For ["I", "love", "pancakes"] the answer is [1, 4, 8], and for ["banana", "kiwi", "fig"] it is [6, 4, 3]. A single word such as ["code"] gives a single length, [4].
Approach: transform every item
This is the mapping pattern: one output for each input, in the same order. Start with an empty vector, visit each word once, and push its length. The result always has exactly as many entries as words.
Step by step
- Create an empty, mutable vector named
lengths. It must bemutbecause each pass of the loop adds to it. There is no type written on it: Rust works out the element type from what gets pushed. - Loop over
&words. The&borrows the vector, so eachwordis a reference to a string and nothing is moved out. - Push
word.len(). The length goes at the end oflengths, so the order of the words is kept. - Return
lengthsafter the loop. A return inside the loop would stop it after the first word.
The solution in Rust
impl Solution {
fn word_lengths(words: Vec<String>) -> Vec<usize> {
let mut lengths = Vec::new();
for word in &words {
lengths.push(word.len());
}
return lengths;
}
}
The Rust details worth a closer look:
- Type inference.
Vec::new()alone doesn't say what the vector holds. The compiler looks atlengths.push(word.len())and at the return typeVec<usize>, and fills inusize. usize.len()returnsusize, the unsigned integer Rust uses for sizes and positions. That is why the function returnsVec<usize>rather thanVec<i32>.- Borrowing. Looping over
&wordsleaveswordsintact. Looping overwordswould work here too, but it would consume the vector for no benefit, since only the lengths are needed. - Bytes, not letters.
len()on aStringcounts bytes. For the English letters in this lesson that equals the number of letters, but"café".len()is 5 while"café".chars().count()is 4. returnwith a semicolon. This style is valid. The more common Rust style ends with the bare expressionlengths, and both behave the same.
The same thing with an iterator
Because this is a one-to-one transformation, Rust also offers a shorter form: words.iter().map(|w| w.len()).collect(). It does exactly what the loop does, and it is worth knowing once loops feel natural. The loop version shows each step, which is why the lesson starts with it.
The empty vector Vec::new() costs nothing until the first push. If you know the final size in advance, Vec::with_capacity(words.len()) reserves the room once and avoids regrowing, but for short inputs the difference is invisible.
Edge cases and common mistakes
- Returning inside the loop. The function would return a vector with one length.
- Forgetting
mut. The compiler rejectspushon a vector that isn't declared mutable. - Uppercase letters. Case doesn't change the length:
["Hello", "WORLD"]gives[5, 5]. - A different return type. Declaring
Vec<i32>would not compile unless each length is converted withas i32.
Testing
["I", "love", "pancakes"]gives[1, 4, 8].["banana", "kiwi", "fig"]gives[6, 4, 3].["code"]gives[4].["Hello", "WORLD"]gives[5, 5].
