Getting Started Exercise: MAPS Implementing Word Counts (WordCount)
As a basic exercise for the entry of Go language, the use of MAPS (mapping) is one of the key knowledge points, and word counting exercise is a classic case of consolidating MAPS usage. This article will record in detail the implementation process, core ideas, code analysis, and key knowledge points involved in the exercise.
1. Description of exercise requirements
The core requirement of this exercise is to implement a function called WordCount, which receives a string parameter s and returns a map[string]The value of the int type, where the key is each ‘word’ in the string, and value is the number of times the word appears in the string.
Exercise provides a basic code framework, and also prompts that you can use the Strings.fields function to assist implementation, and finally run the test suite through the wc.test function to verify the correctness of the function implementation.
The initial basic code is as follows:
package main
import (
"golang.org/x/tour/wc"
)
func WordCount(s string) map[string]int {
return map[string]int{"x": 1} // 占位代码,需完善
}
func main() {
wc.Test(WordCount)
}
Second, the core ideas
To achieve word counting, the core needs to complete 3 steps, the idea is clear and suitable for the characteristics of the Go language:
- Create an empty mapping (map) to store words and corresponding counts, the keys of map are String type (word), and the value is int type (count);
- Split the input string by ‘word’, and use the strings.fields function to automatically process whitespace characters (spaces, tabs, newlines, etc.), and then get the word slice after segmentation;
- Trace the word slice, count each word, and each time the word is encountered, add 1 to the corresponding value in the map, and finally return the map.
3. Complete code after improvement
Combined with the above ideas, the completed code is as follows, and the key steps have been added to facilitate understanding:
package main
import (
"strings" // 导入 strings 包,使用 Fields 函数分割单词
"golang.org/x/tour/wc"
)
// WordCount 统计字符串中每个单词的出现次数
func WordCount(s string) map[string]int {
// 1. 创建一个空的 map,用于存储单词和对应的计数
wordMap := make(map[string]int)
// 2. 使用 strings.Fields 分割字符串,按空格/制表符/换行符分割成单词切片
words := strings.Fields(s)
// 3. 遍历单词切片,统计每个单词的数量
for _, word := range words {
wordMap[word]++ // 单词每出现一次,对应计数 +1
}
// 4. 返回统计结果
return wordMap
}
func main() {
// 运行测试函数,验证 WordCount 是否正确
wc.Test(WordCount)
}
The analysis of key knowledge points
This exercise focuses on the use of MAPS in the Go language, and also involves the basic usage of the Strings package. The following is the detailed analysis of the core knowledge points to help deepen the understanding:
- Initialization and use of Maps
In the Go language, there are two ways to initialize maps: one is to directly use map literals (such as maps in the initial code[string]int{‘x’: 1}), suitable for scenarios with known initial key-value pairs; the other is to use the make function (make(map)[string]int)), suitable for scenarios that initially add key-value pairs for empty and subsequent dynamics, and is also the first choice for this exercise.
Special note: when accessing a key that does not exist in the map, an error will not be reported, and the default value of the value type will be returned (the default value of the int type is 0), which is also a direct use of WordMap.[word]Reason for ++ – When a certain word is encountered for the first time, its corresponding value is 0, and then it becomes 1 after ++, and it is accumulated in sequence after encountering it again. - The role of the Strings.fields function
The Strings.fields function is a common function of the Strings package in the Go language standard library.[]string). The whitespace characters here include spaces, tabs (\t), line breaks (\n), etc., and will automatically ignore continuous whitespace characters, without us manually processing extra spaces, which greatly simplifies the logic of word segmentation.
For example: if the input string is ‘Hello world go’ (there are two spaces between world and go), the slice obtained after processing by Strings.fields is[‘hello’, ‘world’, ‘go’], which automatically filters the extra spaces, which is very suitable for word counting scenes. - loop through slices
In this exercise, the for range loop is used to traverse word slices. The for range loop is a common way of traversing slices, maps and other collections in the Go language. The syntax is for index, and the value := range collection. Here we only need to use the ‘value’ (that is, the word) in the slice, so ignore the underscore (_) of the index and avoid compiling errors of unused variables.
5. Test results and verification
After completing the code, run the program, and the wc.test function will automatically execute a series of test cases to verify the correctness of the wordcount function. If the implementation is correct, the console will output ‘pass’, indicating that all test cases have passed; if there is an error, it will output a specific error message, prompting which test case has not passed, so that we can troubleshoot the problem.
For example, when the input string is ‘I am learning go go’, the function should return the map[string]int{‘i’:1, ‘am’:1, ‘learning’:1, ‘go’:2}, the test suite will automatically verify that the result is correct. as shown in Figure 1

/app/go-tour # cd exercise-maps/
/app/go-tour/exercise-maps # go run main.go
PASS
f("I am learning Go!") =
map[string]int{"Go!":1, "I":1, "am":1, "learning":1}
PASS
f("The quick brown fox jumped over the lazy dog.") =
map[string]int{"The":1, "brown":1, "dog.":1, "fox":1, "jumped":1, "lazy":1, "over":1, "quick":1, "the":1}
PASS
f("I ate a donut. Then I ate another donut.") =
map[string]int{"I":2, "Then":1, "a":1, "another":1, "ate":2, "donut.":2}
PASS
f("A man a plan a canal panama.") =
map[string]int{"A":1, "a":2, "canal":1, "man":1, "panama.":1, "plan":1}
6. Learning experience
This exercise seems simple, but it covers the core usage of Maps in the Go language, the basic functions of the Strings package, and the skills of loop traversal, which is very suitable for the entry stage to consolidate knowledge points.
For me, who was just starting to learn Go language by myself, through this exercise, I not only mastered the initialization of map and the addition and modification of key-value pairs, but also learned to use the help of Standard library functions simplify the development process – do not need to manually divide the string and process blank characters, which reflects the ‘concise and efficient’ design concept of the Go language.
In addition, by writing comments and sorting out ideas, the understanding of the code has also been deepened, and similar counting scenarios will be encountered in the future, and the ideas of this exercise can also be quickly reused.
7. Expand thinking
If you want to further expand this exercise, you can try the following requirements to consolidate more knowledge points:
- Ignore case statistics: for example, treat ‘go’ and ‘go’ as the same word, and then count the words into lowercase or uppercase through the Strings.tolower or Strings.toupper functions.
- To deal with punctuation marks: For example, the string contains ‘hello’, ‘world!’, and the punctuation marks need to be removed before counting the words;
- Count the longest words: While counting, record the words that appear the most and their occurrences.
1 Response
[…] the previous articleMaps word counting exercisesAfter this, another classic exercise in the introduction of Go language – using closure to […]