Start learning free

LESSON 5 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v1 in Rust: First 10 Lines with min and join

Practice Read the full explanation

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

fn head(lines: Vec<String>) -> String

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Compute the end index, capping it at lines.len() so a short input never panics. Then slice the vector and call join("\n") — Rust string slices have a built-in join.

Compute let end = lines.len().min(10), then return lines[0..end].join("\n").

The full solution:
impl Solution {
    fn head(lines: Vec<String>) -> String {
        let end = lines.len().min(10);
        lines[0..end].join("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Head V1 in Rust, explained

    Problem overview

    This project builds a small version of the Unix head command. Version 1 is fixed at ten lines: head(lines: Vec<String>) -> String returns the first 10 lines joined by newline characters. With fewer than 10 lines it returns all of them, and with no lines it returns the empty string.

    With the thirteen lines "a" to "m" the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj", the first ten. With ["a", "b", "c"] the result is "a\nb\nc".

    Approach: clamp the length, slice, join

    Asking for the first ten items of a shorter vector is a trap in Rust: slicing past the end panics rather than quietly returning what is there. The way around it is to decide how many lines can actually be taken before slicing. That count is the smaller of the number of lines and 10, and it is never larger than the vector.

    With that count in hand, two ready-made tools finish the job: a range slice picks the lines, and join glues them with a newline between each pair, never after the last. No loop is needed.

    Step by step

    1. Clamp. let end = lines.len().min(10);. Every integer type has a min method that returns the smaller of the value and its argument. With 13 lines, end is 10; with 3 lines, it is 3; with none, it is 0.
    2. Slice and join. lines[0..end] is the items from index 0 up to, but not including, end. Then .join("\n") builds a String with the separator between neighbours. Without a semicolon, the expression is the function's result.

    The solution in Rust

    impl Solution {
        fn head(lines: Vec<String>) -> String {
            let end = lines.len().min(10);
            lines[0..end].join("\n")
        }
    }
    

    Rust details:

    • lines.len() is a usize, so min(10) works with the literal 10, which Rust reads as a usize here. No cast is needed in this version.
    • lines[0..end] is a slice, a view into the vector's memory with no copying. It is unsized, which is why it is used right away through a method call, not stored in a variable. join on a slice of strings returns a new String.
    • Because end is never greater than lines.len(), the slice is always valid, and for an empty vector lines[0..0] is an empty slice, which joins to "".

    The function takes lines by value, but nothing is moved out of it: slicing borrows the strings, and join copies their text into the new result string. Ten is a fixed limit here, so it appears as a literal in the code.

    Complexity

    Only the selected lines are copied into the result, so time and space are proportional to the number of lines returned, at most 10 of them, plus their lengths. In terms of line count that is constant.

    Edge cases and common mistakes

    • Slicing without clamping. lines[0..10] on a three-line vector panics at run time. The min call prevents that.
    • Exactly 10 lines. end is 10 and all lines come back, with no trailing newline.
    • Empty input. end is 0 and the result is "".
    • A trailing newline. A loop that appends "\n" after every line leaves one at the end; join only places separators between lines.

    Testing

    a to m (13 lines)  ->  "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    ["a", "b", "c"]    ->  "a\nb\nc"
    a to j (10 lines)  ->  "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    []                 ->  ""
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free