Problem overview
The function longWords takes a slice of strings, words, and an integer n. It returns a new slice with the words that have more than n characters, in the order they had in words. A word with exactly n characters is left out, and if nothing qualifies, the result is empty.
With ["apple", "kiwi", "banana", "fig"] and n = 4, "apple" (5) and "banana" (6) pass. "kiwi" has exactly 4 characters, so it fails the test, and "fig" has 3. The result is [apple banana].
Approach: build a new slice as you go
This is the filter pattern: look at each element once, test it, and copy the ones that pass into a result. The input is never changed. Because the loop visits the words from first to last and each passing word goes at the end of the result, the original order is kept without any extra work.
Step by step
- Create an empty result.
[]string{}is a slice with no elements, ready to grow. - Loop over the words.
for _, word := range wordsgives each element in turn.rangeproduces an index and a value; the index is not needed, so it is assigned to the blank identifier_. - Test the length.
len(word) > nis true only when the word is strictly longer thann. Using>=would wrongly keep words of exactlyncharacters. - Append the passing word.
appendreturns the grown slice, so the result must be stored back inresult. - Return the result after the loop.
Tracing the example
With n = 4, the loop makes these decisions:
| word | len(word) | len(word) > 4 | result afterwards |
|---|---|---|---|
| apple | 5 | true | [apple] |
| kiwi | 4 | false | [apple] |
| banana | 6 | true | [apple banana] |
| fig | 3 | false | [apple banana] |
Only the rows with true change result, and they add to its end, so "apple" stays ahead of "banana".
The solution in Go
func longWords(words []string, n int) []string {
result := []string{}
for _, word := range words {
if len(word) > n {
result = append(result, word)
}
}
return result
}
Go details worth knowing
append(result, word)on its own line does nothing useful. It may allocate a bigger array and returns a slice describing it, so the line must beresult = append(result, word). Go also reports the unused result ofappendas a compile error.lenon a string counts bytes, not characters. For the lowercase English letters in this lesson the two are the same. A word like"héllo"has 5 characters butlengives 6, becauseétakes two bytes in UTF-8. Counting characters would needlen([]rune(word)).- Starting with
[]string{}rather thanvar result []stringmeans the function returns an empty, non-nil slice when nothing matches. Printing either one shows[], but the two differ when compared withnil.
Edge cases and common mistakes
- Nothing long enough.
["hi", "to", "be"]withn = 3gives[], a slice of length 0. - Repeated words stay.
["go", "went", "gone", "went"]withn = 3gives[went gone went]: the filter tests each word, not whether it has been seen before. n = 0. Every word has at least one letter, so withn = 0all of them pass.["a", "bb"]returns[a bb].- Forgetting to store
append's result leavesresultempty. - Returning inside the loop would stop at the first long word instead of collecting them all.
Testing
Try these inputs in the editor above:
["apple", "kiwi", "banana", "fig"],n = 4returns[apple banana].["hi", "to", "be"],n = 3returns[].["go", "went", "gone", "went"],n = 3returns[went gone went].
