Go语言现代web开发07 map字典
Maps are complex data types used to store key-value pairs. Each key can appear only once on the map and can be used to find the value paired with that key. The default value for the map is nil. A nil map has no keys and keys cannot be added.
映射是用于存储键值对的复杂数据类型。每个键只能在映射上出现一次,并且可以用来查找与该键配对的值。映射的默认值为nil。nil映射没有键,也不能添加键。
Function make() will create and initialize a map of the given type. The key type is defined between square brackets and the value type is defined at the end. The returned map will be empty. This statement will create and initialize the map with a string key and string value.
make()函数将创建并初始化给定类型的映射。键类型在方括号之间定义,值类型在末尾定义。返回的映射将为空。该语句将使用字符串键和字符串值创建并初始化映射。
var countryMap = make(map[string]string)
Without make() function, the var statement will define a nil map which will be more or less useless.
如果没有make()函数,var语句将定义一个nil映射,这将或多或少毫无用处。
The following operations can be executed on maps:
- Insert and update elements
- Get element
- Test if the key is present
在map上可以执行如下操作:
- 插入和更新元素
- 获取元素
- 测试是否存在密钥
countryMap["fr"] = "France"
country = countryMap["fr"]
delete(countryMap, "fr")
country, ok = countryMap["fr"]
If the key is in the map, the value true will be assigned to variable ok and the elements value will be assigned to country, otherwise, the value false will be assigned to variable ok and nill will be assigned to country.
如果键在map中,则值true将分配给变量ok,元素值将分配给country,否则,值false将分配给变量ok,值nil将分配给country。
The following example shows map creation and usage of described operations:
下面的例子展示了映射的创建和所描述操作的使用:
var countryMap = make(map[string]string)
countryMap["fr"] = "France"
country := countryMap["fr"]
fmt.Println("Country in map is:", country)
delete(countryMap, "fr")
if _, ok := countryMap["fr"]; ok {
fmt.Println("Country is still in map")
} else {
fmt.Println("Country is not in map")
}
In the code is sucessfully executed, the following output will be displayed.
在代码执行成功后,将显示如下输出。
Country in map is: France
Country is not in map
If we use integers for keys, they don’t have to be in order (0, 1, 2, 3, 4 …). For example, if we have a map that represents the basketball team (five players), we can use shirt numbers as keys, and player names as values. It is a regular situation that we use these keys: 3, 9, 10, 12, 32. If we need ordered keys, maybe map is not a good solution for our problem and we should use a slice instead.
如果我们使用整数作为键,它们不必按顺序排列(0,1,2,3,4…)。例如,如果我们有一个表示篮球队(五名球员)的地图,我们可以使用球衣号码作为键,并使用球员姓名作为值。通常情况下,我们使用这些键:3,9,10,12,32。如果我们需要有序键,也许map不是解决问题的好方法,我们应该使用slice。