Start learning free

LESSON 370 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v4 — Negative n drops the tail in Go

Practice

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

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

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

Branch on the sign of n with an early return. When n < 0, slice up to max(0, len(lines)+n) (the max floors a too-large |n|); otherwise slice up to min(len(lines), n). Stitch the slice with strings.Join(..., "\n").

if n < 0 {
    return strings.Join(lines[:max(0, len(lines)+n)], "\n")
}
return strings.Join(lines[:min(len(lines), n)], "\n")


The full solution:
func head(lines []string, n int) string {
    if n < 0 {
        return strings.Join(lines[:max(0, len(lines)+n)], "\n")
    }
    return strings.Join(lines[:min(len(lines), n)], "\n")
}

STEP 1 OF 3
    Ctrl + Enter to check

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