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
- Compute
endwith:=asmin(n, len(lines)). With 5 lines andn = 8it is 5, and withn = 3it is 3. - 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, sominagainstlen(lines)is the right guard here. - Built-in
min. It works on ints, so no import is needed for it. Thestringspackage is still needed forJoin. - Nil and empty slices.
len(nil)is 0, soendis 0, andlines[:0]is allowed on a nil slice.strings.Joinof an empty slice is"". - The assumption about negative
n. Withn < 0,minreturns the negative number, and slicing with a negative end panics. Forn = -1the message isslice 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 oncenexceeds the capacity. nequal to the length. The clamp changes nothing and every line is returned.- Using
maxby 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
nis large. It stops at the last real line. - Negative
n. It isn't handled in this version, and it panics as described above.
