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 }

__EOF__

本文作者RoadWide
本文链接https://www.cnblogs.com/roadwide/p/17135754.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   roadwide  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-02-19 python使用print写文件
点击右上角即可分享
微信分享提示