Start learning free

LESSON 7 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v3 in Go: Capping n with min

Practice Read the full explanation

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

    GO · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in Go, explained

    Problem overview

    Version 3 of the head tool keeps the signature head(lines []string, n int) string, but now n may be larger than the number of lines. In that case the function returns all the lines: no crash and no padding. It still assumes n >= 0. With n = 0, or with no lines, the result is the empty string.

    For ["alpha", "beta", "gamma"] and n = 10 the result is "alpha\nbeta\ngamma". The previous version indexed lines[i] in a loop and would panic here.

    Approach: clamp the count, then slice

    The only new problem is a count that is too big. The fix is to use the smaller of n and len(lines) as the number of lines to take. With the count clamped, a slice lines[:end] is always valid, and strings.Join turns it into the final string. Nothing else needs a special case.

    The same two lines solve the first version, where the cap was the constant 10. Only the number being clamped changes.

    Step by step

    1. Compute end with := as min(n, len(lines)). With 5 lines and n = 8 it is 5, and with n = 3 it is 3.
    2. Return the joined slice: strings.Join(lines[:end], "\n").

    The solution in Go

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

    The Go details:

    • Slice bounds are checked at run time. Slicing with an end beyond the slice's capacity panics with slice bounds out of range. A slice made by a literal has capacity equal to its length, so min against len(lines) is the right guard here.
    • Built-in min. It works on ints, so no import is needed for it. The strings package is still needed for Join.
    • Nil and empty slices. len(nil) is 0, so end is 0, and lines[:0] is allowed on a nil slice. strings.Join of an empty slice is "".
    • The assumption about negative n. With n < 0, min returns the negative number, and slicing with a negative end panics. For n = -1 the message is slice bounds out of range [:-1].

    Why the guard is len, not cap

    Go allows a slice expression to reach past len as long as it stays within cap. Take all := []string{"a", "b", "c", "d", "e"} and part := all[:3]. Then part has length 3 and capacity 5, and part[:5] doesn't panic: it brings back "d" and "e", which still sit in the shared array. Joining part[:5] gives "a\nb\nc\nd\ne". Clamping with min(n, len(lines)) avoids that surprise, and head(part, 5) correctly gives "a\nb\nc". The lesson's inputs never have spare capacity, but the clamp against len is what makes the function right for every slice, and that is the behaviour the statement asks for: no more lines than the input has.

    Tracing

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

    ["alpha", "beta", "gamma"], n = 10  ->  "alpha\nbeta\ngamma"
    5 lines "alpha".."epsilon", n = 2    ->  "alpha\nbeta"
    nil, n = 4                          ->  ""
    5 lines, n = 0                      ->  ""
    

    Edge cases and common mistakes

    • A big n. Without the clamp, lines[:n] panics once n exceeds the capacity.
    • n equal to the length. The clamp changes nothing and every line is returned.
    • Using max by mistake. max(n, len(lines)) picks the larger number and breaks the slice. The bound has to be the smaller one.
    • Padding. The result never contains extra empty lines when n is large. It stops at the last real line.
    • Negative n. It isn't handled in this version, and it panics as described above.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free