Go language is an open source programming language that is efficient and concise. One of its data structures is map. In the Go language, map is a "key-value pair" data structure that can be used to store a series of unordered key-value pairs. This article will introduce in detail the basic use of map in Go language and provide specific code examples.
In the Go language, you can use the built-in make function to create an empty map. The syntax is as follows:
m := make(map[string]int) // 创建一个键为字符串,值为整数的map
To add key-value pairs to the map, you can use map[key] = value. The example is as follows:
m := make(map[string]int) m["apple"] = 5 m["banana"] = 3
Get it by key For the corresponding value, you can use map[key]. The example is as follows:
fmt.Println(m["apple"]) // 输出:5
When getting the value, sometimes you need to determine whether the key exists. You can Use the "comma ok" syntax, the example is as follows:
value, ok := m["orange"] if ok { fmt.Println("orange的值为:", value) } else { fmt.Println("orange不存在") }
To delete the key-value pair in the map, you can use the delete function, the example is as follows:
delete(m, "banana")
Use the for loop and range keyword to traverse the key-value pairs in the map. The example is as follows:
for key, value := range m { fmt.Println(key, ":", value) }
You can use the len function to get the number of key-value pairs in the map. The example is as follows:
fmt.Println("map的长度为:", len(m))
Through the above code examples, we can clearly understand how to use the map data structure in the Go language. The flexibility and efficiency of map make it one of the commonly used data structures in the Go language. Hope this article is helpful to beginners.
The above is the detailed content of Basic map usage in Go language. For more information, please follow other related articles on the PHP Chinese website!