Golang基础-Maps

常见用法

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{}    // 大括号相当于初始化为空,和下面的ages对照
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
}
posted @ 2023-02-19 22:00  roadwide  阅读(20)  评论(0编辑  收藏  举报