Start learning free

LESSON 5 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v1 in Go: The First 10 Lines with Slicing

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:

func head(lines []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 len(lines) so a short input never panics. Then slice and call strings.Join with "\n" as the separator.

Compute end := min(len(lines), 10), then return strings.Join(lines[:end], "\n").

The full solution:
func head(lines []string) string {
    end := min(len(lines), 10)
    return strings.Join(lines[:end], "\n")
}

STEP 1 OF 2
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Head V1 in Go, explained

    Problem overview

    This is the first version of a small tool modelled on the Unix head command. The function head(lines []string) string returns the first 10 lines of its input, joined by newline characters. With fewer than 10 lines it returns all of them, and with none it returns the empty string.

    For the 13 lines a to m, the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj".

    Approach: cap the length, slice, join

    The job has two parts. First work out how many lines to keep, which is 10 or the number of lines, whichever is smaller. Then take that many lines from the front and join them. Slicing takes care of the second part in one expression, so the only decision is the count.

    The count matters because Go checks slice bounds when the program runs: asking for lines[:10] on a slice that has 3 items and no spare room panics with a "slice bounds out of range" error. Taking the smaller of the two numbers means the bound is never past the end.

    Step by step

    1. Compute end with := as min(len(lines), 10). With 13 lines this is 10, with 3 lines it is 3.
    2. Return the joined slice. lines[:end] is the items from position 0 up to, but not including, end, and strings.Join glues them with "\n" between each two.

    The solution in Go

    func head(lines []string) string {
        end := min(len(lines), 10)
        return strings.Join(lines[:end], "\n")
    }
    

    The Go details:

    • Built-in min. Since Go 1.21, min and max are built in and take any ordered values. Go 1.22 has them, so no helper function is needed.
    • Slice expressions. s[:end] means s[0:end]. The end index is exclusive and may equal the length. It must not exceed the slice's capacity, which is why the cap is needed.
    • A slice shares memory. lines[:end] doesn't copy anything. It is a new view of the same array, which is fine here because strings.Join only reads it.
    • strings.Join and empty input. It puts the separator between items only, and for an empty slice, including a nil one, it returns "". For a single item it returns that item with no separator. This is why no special case for empty input is needed.
    • The strings import. The function relies on the strings package.

    Tracing

    These inputs and results come from running the function (shown as Go string literals):

    13 lines "a".."m"  ->  "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    3 lines "a".."c"   ->  "a\nb\nc"
    10 lines "a".."j"  ->  "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    nil                ->  ""
    

    Edge cases and common mistakes

    • Slicing without the cap. lines[:10] on a short slice panics at run time. The compiler can't catch it because the length is known only when the program runs.
    • Exactly 10 lines. Nothing is dropped and no extra newline appears.
    • Off by one. Writing lines[:end+1] or lines[:9] returns 11 or 9 lines. The end index is exclusive, so 10 is the right bound for 10 lines.
    • Joining with a trailing newline. The result has newlines between lines only, so nothing follows the last one.
    • Empty input. An empty slice gives end = 0 and lines[:0] is valid, so the result is "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free