Start learning free

LESSON 369 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v3 — Cap n at len(lines) in Go

Practice

Same signature as v2, but now n may be larger than the number of lines. If n > len(lines) simply return all the lines (don't crash, don't pad). For this version assume n ≥ 0. If n is 0, or there are no lines, the result is the empty string.

Function signature:

func head(lines []string, n int) string

Example:

Input: lines = ["alpha", "beta", "gamma"], n = 10

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Slicing lines[:n] past the end panics in Go, so clamp n with min(n, len(lines)) before slicing. strings.Join then stitches the prefix together with newlines.

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


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

STEP 1 OF 2
    Ctrl + Enter to check

    Head V3 in Go

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free