Problem overview
This is the first version of a small tool modelled on the Unix head command. The function head(lines []string) string returns the first 10 lines of its input, joined by newline characters. With fewer than 10 lines it returns all of them, and with none it returns the empty string.
For the 13 lines a to m, the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj".
Approach: cap the length, slice, join
The job has two parts. First work out how many lines to keep, which is 10 or the number of lines, whichever is smaller. Then take that many lines from the front and join them. Slicing takes care of the second part in one expression, so the only decision is the count.
The count matters because Go checks slice bounds when the program runs: asking for lines[:10] on a slice that has 3 items and no spare room panics with a "slice bounds out of range" error. Taking the smaller of the two numbers means the bound is never past the end.
Step by step
- Compute
endwith:=asmin(len(lines), 10). With 13 lines this is 10, with 3 lines it is 3. - Return the joined slice.
lines[:end]is the items from position 0 up to, but not including,end, andstrings.Joinglues them with"\n"between each two.
The solution in Go
func head(lines []string) string {
end := min(len(lines), 10)
return strings.Join(lines[:end], "\n")
}
The Go details:
- Built-in
min. Since Go 1.21,minandmaxare built in and take any ordered values. Go 1.22 has them, so no helper function is needed. - Slice expressions.
s[:end]meanss[0:end]. The end index is exclusive and may equal the length. It must not exceed the slice's capacity, which is why the cap is needed. - A slice shares memory.
lines[:end]doesn't copy anything. It is a new view of the same array, which is fine here becausestrings.Joinonly reads it. strings.Joinand empty input. It puts the separator between items only, and for an empty slice, including a nil one, it returns"". For a single item it returns that item with no separator. This is why no special case for empty input is needed.- The
stringsimport. The function relies on thestringspackage.
Tracing
These inputs and results come from running the function (shown as Go string literals):
13 lines "a".."m" -> "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
3 lines "a".."c" -> "a\nb\nc"
10 lines "a".."j" -> "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
nil -> ""
Edge cases and common mistakes
- Slicing without the cap.
lines[:10]on a short slice panics at run time. The compiler can't catch it because the length is known only when the program runs. - Exactly 10 lines. Nothing is dropped and no extra newline appears.
- Off by one. Writing
lines[:end+1]orlines[:9]returns 11 or 9 lines. The end index is exclusive, so 10 is the right bound for 10 lines. - Joining with a trailing newline. The result has newlines between lines only, so nothing follows the last one.
- Empty input. An empty slice gives
end = 0andlines[:0]is valid, so the result is"".
