Start learning free

LESSON 367 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v1 — First 10 Lines in Go

Practice

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

    Head V1 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