在 Go 中,map 是一种内置的数据类型,它把键映射到值。
在其他编程语言里,你可能已经熟悉类似 map 的概念,比如字典、哈希表、键值存储或关联数组。
从语法上看,map 长这样:
map[KeyType]ElementType
另外还有一点很重要:每个键都是唯一的,也就是说,对同一个键赋值两次,会覆盖这个键对应的值。
要创建 map,可以这样写:
// With map literal
foo := map[string]int{}
或者
// or with make function
foo := make(map[string]int)
下面是一些你可以对 map 进行的操作
// Add a value in a map with the `=` operator:
foo["bar"] = 42
// Here we update the element of `bar`
foo["bar"] = 73
// To retrieve a map value, you can use
baz := foo["bar"]
// To delete an item from a map, you can use
delete(foo, "bar")
如果你试图获取 map 中不存在的键对应的值,它会返回值类型的零值。
这可能会让你感到困惑,尤其是当你的 ElementType 的默认值(例如 int 的 0)本身就是一个有效值时。
要检查某个键是否存在于 map 中,可以使用
value, exists := foo["baz"]
// If the key "baz" does not exist,
// value: 0; exists: false
你的一位朋友经营着一家叫Gross Store的老式批发店。 店名来自店里售卖商品的计量单位:全都以 gross 单位 计。 你的朋友请你为他的店实现一套销售点(POS)系统。 首先,你要为它做一个原型。 在原型中,你的系统只记录数量。 你的朋友给了你一份计量单位列表来帮你:
| 单位 | 数值 |
|---|---|
| quarter_of_a_dozen | 3 |
| half_of_a_dozen | 6 |
| dozen | 12 |
| small_gross | 120 |
| gross | 144 |
| great_gross | 1728 |
要使用这些计量单位,你需要把它们存到程序中。
units := Units()
fmt.Println(units)
// Output: map[...] with entries like ("dozen": 12)
你需要实现一个函数,为顾客创建一份新的(空)账单。
bill := NewBill()
fmt.Println(bill)
// Output: map[]
为此,你需要:
unit不在units映射中,返回false。bill,以商品名作为键,然后返回true。unit对应的数量增加它的数量。bill := NewBill()
units := Units()
ok := AddItem(bill, units, "carrot", "dozen")
fmt.Println(ok)
// Output: true (since dozen is a valid unit)
注意,返回值的类型是
bool。
为此,你需要:
false。unit不在units映射中,返回false。false。bill中彻底移除,然后返回true。true。bill := NewBill()
units := Units()
ok := RemoveItem(bill, units, "carrot", "dozen")
fmt.Println(ok)
// Output: false (because there are no carrots in the bill)
注意,返回值的类型是
bool。
为此,你需要:
item不在账单中,返回0和false。bill中的数量和true。bill := map[string]int{"carrot": 12, "grapes": 3}
qty, ok := GetItem(bill, "carrot")
fmt.Println(qty)
// Output: 12
fmt.Println(ok)
// Output: true
注意,返回值的类型是
int和bool。