Problem overview
This first version of a small tool modelled on the Unix wc command counts lines. The function countLines(lines []string) int receives a slice of strings, one per line, and returns how many there are.
For ["hello", "world", "foo", "bar", "baz"] the answer is 5. Every entry is one line, even an empty string "", and an empty slice has 0 lines. The next version builds on this one.
Approach: the length is the answer
The input is already split into lines, so counting them means asking the slice how long it is. There is no loop to write and no entry to inspect: a blank line counts exactly like any other.
Step by step
- Return
len(lines). The built-inlengives the number of items in a slice.
The solution in Go
func countLines(lines []string) int {
return len(lines)
}
The Go details:
lenis a built-in function. It works on slices, arrays, strings, maps and channels, and returns anint, which matches the function's return type. No conversion is needed.- A nil slice has length 0. A
var lines []stringthat was never assigned isnil, andlenof it is 0, so there is no need to check fornilfirst. - Length against capacity.
lencounts the items in the slice. The separate built-incapreports the room in the backing array and isn't what this function wants.
What a line is in this project
The tools in this chapter work on a slice of lines rather than on raw text, and that choice keeps each one small. Reading a file and splitting it at newlines is a separate job. Once the text is a []string, line-based tools such as this one reduce to slice operations.
A line is whatever sits in one slot, so the slice []string{"a", "", "b"} has 3 lines even though the middle one has no characters. The count doesn't depend on what the strings contain, on how long they are, or on whether they repeat.
len means different things on different types
The same built-in counts different units depending on what it is given. On a slice it counts items, which is what this lesson needs. On a string it counts bytes, not characters: len("héllo") is 6 because é takes two bytes in UTF-8, while len([]rune("héllo")) is 5. So len(lines) is the number of lines, but len(lines[0]) is the byte length of the first line, and it is easy to mix the two up when a function receives both a slice and its entries.
Tracing
These inputs and results come from running the function:
["hello", "world", "foo", "bar", "baz"] -> 5
["", ""] -> 2
nil -> 0
[]string{} -> 0
A var s []string that was never assigned has length 0 and is equal to nil, and countLines(s) returns 0 for it too.
Edge cases and common mistakes
- Blank lines are lines. Two empty strings count as two lines, so don't skip them.
- Counting newline characters instead. The input holds lines, not one text, so there are no
\ncharacters to count. - Returning the wrong type. The function returns an
int. Returning a string such asstrconv.Itoa(len(lines))doesn't compile against this signature.
