Start learning free

LESSON 226 OF 293 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Lengths in Rust: Collecting len() Results in a Vec

Practice Read the full explanation

Given a Vec of strings words, return a Vec of integers with the length of every word, in the same order as the words.

The length of a word is the number of letters it has.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: [1, 4, 8]
Explanation: "I" has 1 letter, "love" has 4 and "pancakes" has 8.

Example 2:

Input: words = ["banana", "kiwi", "fig"]
Output: [6, 4, 3]
Explanation: The lengths keep the order of the words: first "banana", then "kiwi", then "fig".

Example 3:

Input: words = ["code"]
Output: [4]
Explanation: One word gives one length.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • The result has one length per word, in the same order as words.
STEP 1 OF 4
    Ctrl + Enter to check

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in Rust, explained

    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

    1. Create an empty, mutable vector named lengths. It must be mut because 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.
    2. Loop over &words. The & borrows the vector, so each word is a reference to a string and nothing is moved out.
    3. Push word.len(). The length goes at the end of lengths, so the order of the words is kept.
    4. Return lengths after 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 at lengths.push(word.len()) and at the return type Vec<usize>, and fills in usize.
    • usize. len() returns usize, the unsigned integer Rust uses for sizes and positions. That is why the function returns Vec<usize> rather than Vec<i32>.
    • Borrowing. Looping over &words leaves words intact. Looping over words would work here too, but it would consume the vector for no benefit, since only the lengths are needed.
    • Bytes, not letters. len() on a String counts 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.
    • return with a semicolon. This style is valid. The more common Rust style ends with the bare expression lengths, 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 rejects push on 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 with as i32.

    Testing

    • ["I", "love", "pancakes"] gives [1, 4, 8].
    • ["banana", "kiwi", "fig"] gives [6, 4, 3].
    • ["code"] gives [4].
    • ["Hello", "WORLD"] gives [5, 5].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free