Problem overview
Version 2 of the head tool takes a count: head(lines []string, n int) string returns the first n lines joined by newline characters. For this version n is assumed to satisfy 0 <= n <= len(lines). If n is 0, the result is the empty string.
For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3 the result is "alpha\nbeta\ngamma". The previous version always kept 10 lines; now the count comes from the caller.
Approach: build the string line by line
This version builds the result with a loop that runs n times. In each pass, it adds a newline first, unless this is the first line, and then the line itself. Putting the separator before each line except the first gives newlines between lines and none at the end.
Because the assumption is that n never exceeds the number of lines, the loop can use lines[i] for every i below n without any clamping.
Step by step
- Start with an empty
result. - Loop with
ifrom 0 whilei < n. The index runs from 0 ton - 1, so exactlynlines are visited. - Add a newline when
i > 0, which is every pass except the first. - Append
lines[i]toresult. - Return
result. Forn = 0the loop never runs, so it is still the empty string.
The solution in Go
func head(lines []string, n int) string {
result := ""
for i := 0; i < n; i++ {
if i > 0 {
result += "\n"
}
result += lines[i]
}
return result
}
The Go details:
- Indexing is checked. Go doesn't read outside a slice. If
nis larger thanlen(lines), the loop panics withindex out of rangewhenireaches the length. With five lines andn = 6, the message isindex out of range [5] with length 5. That is why this version states its assumption. - Negative
ndoesn't fail. The conditioni < nis false at once, so the loop is skipped and the result is"". This lesson doesn't promise anything for negative values. - Strings are immutable. Each
+=makes a new string. For a few lines this is fine. - The loop variable.
iis declared in theforstatement and exists only inside it.
Tracing
These inputs and results come from running the function with the five lines above (shown as Go string literals):
n = 3 -> "alpha\nbeta\ngamma"
n = 0 -> ""
n = 5 -> "alpha\nbeta\ngamma\ndelta\nepsilon"
The slicing alternative
Because the lines already sit in a slice, the same result can come from slicing and joining, as in strings.Join(lines[:n], "\n"). For any n from 0 up to len(lines) it returns the same string as the loop: lines[:0] is empty and joins to "", and lines[:len(lines)] is the whole slice. The loop version is worth writing here because it shows the separator rule in action. It also copies the growing string on every +=, so for large inputs joining is cheaper, since it builds the result in one pass.
Edge cases and common mistakes
n = 0. The empty string comes back, and nothing is indexed.nequal to the length. All lines are returned, and the last valid index isn - 1.- Using
i <= n. The loop would visitn + 1lines and panic whennequals the length. - The separator test. Testing
i > 0puts a newline before every line except the first. Testingi < n-1after the line would also work, but mixing the two styles gives an extra or a missing newline. - A trailing newline. The result has none, since the newline is added before a line and never after it.
