常见用法
var ages map[string]int // 只声明不初始化是nil,赋值会panic: assignment to entry in nil map
fmt.Println(ages == nil) // "true"
fmt.Println(len(ages) == 0) // "true"
// 初始化
foo := map[string]int{}
foo := make(map[string]int)
ages := map[string]int{
"alice": 31,
"charlie": 34,
}
// 删除
delete(foo, "bar")
// 判断key是否存在
value, exists := foo["baz"]
// If the key "baz" does not exist,
// value: 0; exists: false
// 遍历
for name, age := range ages {
fmt.Printf("%s\t%d\n", name, age)
}
for name := range ages {
fmt.Printf("%s\n", name)
}
Exercise
package gross
// Units stores the Gross Store unit measurements.
func Units() map[string]int {
res := map[string]int{
"quarter_of_a_dozen": 3,
"half_of_a_dozen": 6,
"dozen": 12,
"small_gross": 120,
"gross": 144,
"great_gross": 1728,
}
return res
}
// NewBill creates a new bill.
func NewBill() map[string]int {
bill := make(map[string]int) // 必须make,否则不会初始化。只声明不make是nil
return bill
}
// AddItem adds an item to customer bill.
func AddItem(bill, units map[string]int, item, unit string) bool {
if bill == nil {
bill = NewBill()
}
if _, exists := units[unit]; !exists {
return false
}
bill[item] += units[unit]
return true
}
// RemoveItem removes an item from customer bill.
func RemoveItem(bill, units map[string]int, item, unit string) bool {
if bill == nil {
return false
}
if _, exists := bill[item]; !exists {
return false
}
if _, exists := units[unit]; !exists {
return false
}
if bill[item]-units[unit] < 0 {
return false
}
if bill[item] == units[unit] {
delete(bill, item)
} else {
bill[item] -= units[unit]
}
return true
}
// GetItem returns the quantity of an item that the customer has in his/her bill.
func GetItem(bill map[string]int, item string) (int, bool) {
if bill == nil {
return 0, false
}
if _, exists := bill[item]; !exists {
return 0, false
}
return bill[item], true
}
标签:map,return,string,item,int,bill,基础,Golang,Maps
From: https://www.cnblogs.com/roadwide/p/17135754.html