Problem overview
Version 4 of the head tool gives negative values of n a meaning, the same one the real head -n -K has: print all lines except the last K. The signature is still head(lines []string, n int) string. For n < 0, the function returns all the lines except the last |n|. For n >= 0 it behaves like version 3: the first n lines, capped at the input length. When |n| is at least the number of lines, nothing is left and the result is the empty string.
For ["a", "b", "c", "d", "e"] and n = -2 the result is "a\nb\nc".
Approach: one end index for each case
Both cases are the same operation, take the lines from the start up to some end index. Only the way the end is computed differs. For a non-negative n it is min(len(lines), n), as in the previous version. For a negative n, dropping |n| lines from the tail means keeping len(lines) + n lines, because adding a negative number subtracts. With 5 lines and n = -2, that is 3.
That value can fall below zero when more lines are dropped than exist, and a negative end isn't a valid slice bound. Taking max(0, len(lines) + n) stops the count at 0, which yields an empty slice and so the empty string.
Step by step
- Open an
ifforn < 0, since a negative count needs its own calculation. - Return the first
max(0, len(lines)+n)lines joined withstrings.Join(..., "\n"). Themaxis the guard against a negative bound. - After the
if, return the firstmin(len(lines), n)lines joined the same way. Only a non-negativengets here, because theifalready returned for negative values.
The solution in Go
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")
}
The Go details:
- Early return instead of
else. After theifblock returns, the code below it runs only for non-negativen. Go style prefers this to anelsethat wraps the rest of the function. - Built-in
minandmax. Both are built in since Go 1.21, so Go 1.22 needs no helpers. They are mirror images, and each of the two returns guards one side of the valid range. - Both ends clamp. The negative branch uses
maxto stay at or above 0, and the other branch usesminto stay at or below the length. Together they keep every slice bound inside[0, len(lines)]. - The result of
lines[:end]shares the original array. It isn't a copy, which is fine becausestrings.Joinonly reads it.
Tracing
These inputs and results come from running the function with the five lines a to e (shown as Go string literals):
n = -2 -> "a\nb\nc"
n = -1 -> "a\nb\nc\nd"
n = -5 -> ""
n = -9 -> ""
n = 0 -> ""
n = 3 -> "a\nb\nc"
n = 99 -> "a\nb\nc\nd\ne"
nil, n = -1 -> ""
The rows for n = -5 and n = -9 show the clamp: len(lines) + n is 0 and -4, and both become an empty slice.
Edge cases and common mistakes
- Dropping more lines than exist. Without
max(0, ...),n = -9gives the bound-4and the program panics. - Dropping exactly all lines.
n = -5gives a bound of 0, an empty slice and an empty string. - Zero is not negative.
n = 0takes the second branch and returns the empty string, while a negativenof any size never returns all the lines. - Subtracting the wrong way. Writing
len(lines) - nwith a negativengives a bound past the end, which panics. The sumlen(lines) + nis the right one, asnis already negative. - An empty input. With no lines the bound is 0 for any
nbelow zero, so the result is"".
