Start learning free

LESSON 6 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v2 in Rust: First n Lines with a Loop

Practice Read the full explanation

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.len(). If n is 0 the result is the empty string.

Function signature:

fn head(lines: Vec<String>, n: i32) -> String

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Loop with i over 0..n, accumulating each line into a String. Insert a "\n" before every line except the first.

for i in 0..n {
    if i > 0 {
        result += "\n";
    }
    result += &lines[i as usize];
}


The full solution:
impl Solution {
    fn head(lines: Vec<String>, n: i32) -> String {
        let mut result = String::new();
        for i in 0..n {
            if i > 0 {
                result += "\n";
            }
            result += &lines[i as usize];
        }
        return result;
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in Rust, explained

    Problem overview

    Version 2 of the head project takes a second argument: head(lines: Vec<String>, n: i32) -> String returns the first n lines joined by newlines. For this version it may be assumed that 0 <= n <= lines.len(), so n is never more than the number of lines. When n is 0 the result is the empty string.

    For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3 the result is "alpha\nbeta\ngamma".

    Approach: build the string line by line

    The first version fixed the count at 10. Now the count is a parameter, and this version builds the string in a loop that runs n times. The usual rule applies: a newline goes between two lines, so every line except the first gets a newline in front of it. That puts a separator between neighbours and none after the last line.

    The statement promises that n fits inside the vector, so the loop doesn't have to check the length. That promise is why this version is simple, and it also marks where it breaks, as the edge cases below show.

    Step by step

    1. Accumulator. let mut result = String::new(); starts empty, and mut allows appending.
    2. Loop. for i in 0..n counts 0, 1, ..., n - 1. The range excludes n, giving exactly n passes. For n = 0 the loop never runs.
    3. Separator test. if i > 0 is true on every pass but the first.
    4. Newline. Inside it, result += "\n";.
    5. The line. result += &lines[i as usize];. The loop variable has the type of n, which is i32, but a vector is indexed with a usize, so i as usize converts it. The & borrows the text, so it is copied onto result and not moved out of the vector.
    6. Return. return result; after the loop.

    The solution in Rust

    impl Solution {
        fn head(lines: Vec<String>, n: i32) -> String {
            let mut result = String::new();
            for i in 0..n {
                if i > 0 {
                    result += "\n";
                }
                result += &lines[i as usize];
            }
            return result;
        }
    }
    

    Rust details:

    • Rust has no automatic conversion between integer types. lines[i] with an i32 index doesn't compile, so the explicit as usize is required. For the non-negative values this version assumes, the conversion is exact.
    • lines[i as usize] is a String, and &lines[i as usize] a &String that Rust turns into the &str that += wants.
    • Indexing a vector out of bounds panics; it does not return a default value.

    Complexity

    The loop runs n times and each pass copies one line, so time is proportional to the combined length of the first n lines. The result is the only extra storage.

    Edge cases and common mistakes

    • n = 0. The loop doesn't run and the result is "".
    • n equal to the number of lines. All lines come back: for the five-word list and n = 5, the result is "alpha\nbeta\ngamma\ndelta\nepsilon".
    • n larger than the number of lines. This is outside the promise made here. With two lines and n = 3, the third pass indexes position 2 and the program panics with "index out of bounds: the len is 2 but the index is 2". In this version the caller is responsible for keeping n in range.
    • Trailing newline. Adding "\n" after every line leaves one at the end. The i > 0 test avoids it.
    • Forgetting the cast. Indexing with i directly is a compile error, because i is an i32.

    Testing

    alpha..epsilon, n = 3  ->  "alpha\nbeta\ngamma"
    alpha..epsilon, n = 0  ->  ""
    alpha..epsilon, n = 5  ->  "alpha\nbeta\ngamma\ndelta\nepsilon"
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free