Problem overview
The function wordLengths receives a slice of strings, words, and returns a slice of integers: the length of each word, in the same order. For ["I", "love", "pancakes"] the result is [1 4 8].
The input has at least one word, and the words are made of English letters, so a word's length is its number of letters.
Approach: one output per input
This is the "map" pattern: every element of the input produces exactly one element of the output. The new slice starts empty, the loop visits the words in order, and each length is added at the end. Since the order of visiting and the order of adding are the same, the lengths line up with the words.
Step by step
- Start with an empty
[]int. The result holds integers, not strings, so its type differs from the input's. It is declared with:=and grows as values are appended. - Loop with
range.for _, word := range wordsgives each element asword. The first value thatrangeproduces is the index, and_discards it. - Append the length.
len(word)is anint, which matches the slice's element type.appendreturns the longer slice, which goes back intolengths. - Return after the loop. A
returninside the loop would send back after the first word.
Tracing the example
With ["I", "love", "pancakes"], lengths grows by one value per word. After "I" it is [1], after "love" it is [1 4], and after "pancakes" it is [1 4 8]. The loop never skips a word and never adds two values for one word, so the result has as many entries as the input.
Where the lengths go matters as much as what they are: each new value lands at the end, behind the earlier ones, so the position of a length in the result is the position of its word in the input.
The solution in Go
func wordLengths(words []string) []int {
lengths := []int{}
for _, word := range words {
lengths = append(lengths, len(word))
}
return lengths
}
Go details worth knowing
- The loop variable
wordis a copy of the element. Changing it would not changewords; here it is only read. lencounts bytes in a string. That equals the number of letters for plain English letters. For text with accented letters, such as"héllo",lengives 6 whilelen([]rune("héllo"))gives 5.- You could allocate the result up front with
make([]int, len(words))and assignlengths[i]by index. Theappendversion needs no index bookkeeping, and for a slice this size it is just as clear.
Edge cases and common mistakes
- A single word.
["code"]gives[4]. - Uppercase letters count the same as lowercase ones: the length depends on how many letters there are, not on their case.
- Discarding
append's result (writingappend(lengths, len(word))alone) leaveslengthsempty, and Go refuses to compile that line anyway. - Using the index instead of the word. If you keep the index and drop the word, you would add 0, 1, 2 rather than the lengths.
Testing
["I", "love", "pancakes"]returns[1 4 8].["banana", "kiwi", "fig"]returns[6 4 3].["code"]returns[4].
