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
ascast between integer types never fails; it keeps the value if it fits and truncates it otherwise. Ausizeabove 2,147,483,647 would not fit ani32, 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 offreturnand the semicolon, as inlines.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 reportsmismatched typesand says it expectedi32but foundusize.
Testing
["hello", "world", "foo", "bar", "baz"] -> 5
["", ""] -> 2
[] -> 0
["a\nb"] -> 1
