Start learning free

LESSON 9 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc v1 in Rust: Count Lines with len()

Practice Read the full explanation

Build a tiny version of the Unix wc command. Given a list of lines, return the total number of lines as an integer.

Function signature:

fn count_lines(lines: Vec<String>) -> i32

Example:

Input: lines = ["hello", "world", "foo", "bar", "baz"]

Output: 5

Every entry of the list is one line, even an empty string "". An empty list has 0 lines.


The number of lines is just the vector's length. Use lines.len() and cast it to i32.

A one-liner:
impl Solution {
    fn count_lines(lines: Vec<String>) -> i32 {
        return lines.len() as i32;
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Wc V1 in Rust, explained

    Problem overview

    This project builds a small version of the Unix wc command, which counts things in text. Version 1 counts lines. The function count_lines(lines: Vec<String>) -> i32 takes a list of lines and returns how many there are.

    For ["hello", "world", "foo", "bar", "baz"] the answer is 5. Every entry is one line, even an empty string "", and an empty list has 0 lines.

    Approach: the length is the count

    The input is already split into lines, one string per entry, so the number of lines is the number of entries. There is nothing to loop over or to parse: the vector knows its own length. The only wrinkle is a type mismatch between what the vector reports and what the function must return.

    Step by step

    There is one step. lines.len() returns the number of items in the vector. Its type is usize, the unsigned integer type Rust uses for sizes and indexes, but the function is declared to return an i32. Rust never converts between integer types silently, so the value needs an explicit as i32.

    The solution in Rust

    impl Solution {
        fn count_lines(lines: Vec<String>) -> i32 {
            return lines.len() as i32;
        }
    }
    

    Rust details:

    • The as cast between integer types never fails; it keeps the value if it fits and truncates it otherwise. A usize above 2,147,483,647 would not fit an i32, but a list that long is far outside what this lesson handles.
    • The cast belongs on the number lines.len(), and nothing about the strings themselves is touched. The vector is owned by the function and is simply dropped when it returns.
    • The lesson writes return ... ; explicitly. Leaving off return and the semicolon, as in lines.len() as i32, means the same thing.

    Why the type mismatch exists

    A vector's length can never be negative, and it has to be able to describe the largest vector the machine can hold, so Rust gives it the unsigned, pointer-sized type usize. The lesson's function signature uses i32 instead, a signed 32-bit integer. The compiler won't guess which one is meant, so the conversion is spelled out, and a reader of the code can see exactly where one integer type becomes another. Plain as casts like this one appear again whenever a size has to meet an i32.

    Counting this way takes constant time: a vector stores its length, so len() doesn't walk through the strings.

    Edge cases and common mistakes

    • Empty strings count. ["", ""] has 2 lines, because each entry is a line whether or not it has text.
    • Empty list. len() is 0 and so is the answer.
    • Newlines inside an entry are not counted. ["a\nb"] is one entry and gives 1. This function counts entries, not newline characters.
    • Forgetting the cast. Returning lines.len() directly is a compile error: the compiler reports mismatched types and says it expected i32 but found usize.

    Testing

    ["hello", "world", "foo", "bar", "baz"]  ->  5
    ["", ""]                                  ->  2
    []                                        ->  0
    ["a\nb"]                                  ->  1
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free