Go语言的map以及sort
通过这个例子了解map的使用。
Go语言程序:
// map project main.go package main import ( "fmt" "sort" ) func main() { var countryCapitalMap map[string]string /* 创建集合 */ countryCapitalMap = make(map[string]string) /* map 插入 key-value 对,各个国家对应的首都 */ countryCapitalMap["France"] = "Paris" countryCapitalMap["Italy"] = "Rome" countryCapitalMap["Japan"] = "Tokyo" countryCapitalMap["India"] = "New Delhi" countryCapitalMap["China"] = "Beijing" fmt.Println("Original:") /* 使用 key 输出 map 值 */ for country := range countryCapitalMap { fmt.Println("Capital of", country, "is", countryCapitalMap[country]) } fmt.Println("") /* map 删除 key-value 对 */ delete(countryCapitalMap, "India") fmt.Println("After deletion:") /* 使用 key 输出 map 值 */ for country := range countryCapitalMap { fmt.Println("Capital of", country, "is", countryCapitalMap[country]) } fmt.Println("") /* 映射反转 */ capitalCountryMap := make(map[string]string, len(countryCapitalMap)) for country, capital := range countryCapitalMap { capitalCountryMap[capital] = country } fmt.Println("After the reversal:") for capital := range capitalCountryMap { fmt.Println("Country of", capital, "is", capitalCountryMap[capital]) } fmt.Println("") /* 查看元素在集合中是否存在 */ captial, ok := countryCapitalMap["United States"] /* 如果 ok 是 true, 则存在,否则不存在 */ if ok { fmt.Println("Capital of United States is", captial) } else { fmt.Println("Capital of United States is not present") } fmt.Println("") /* 排序输出 */ var keys []string for k := range countryCapitalMap { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { fmt.Println("Key:", k, "Value:", countryCapitalMap[k]) } }
程序运行结果:
Original: Capital of France is Paris Capital of Italy is Rome Capital of Japan is Tokyo Capital of India is New Delhi Capital of China is Beijing After deletion: Capital of France is Paris Capital of Italy is Rome Capital of Japan is Tokyo Capital of China is Beijing After the reversal: Country of Paris is France Country of Rome is Italy Country of Tokyo is Japan Country of Beijing is China Capital of United States is not present Key: China Value: Beijing Key: France Value: Paris Key: Italy Value: Rome Key: Japan Value: Tokyo
程序说明:
1.map似乎可以直接使用
2.排序可以使用sort包
3.map是无序的需要另外定义一个数组来排序
参考链接:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架