课程表

Go语言课程

工具箱
速查手册

Go 语言Map(集合)

当前位置:免费教程 » 程序设计 » Go语言

Map 是一种无序的键值对的集合。Map 最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据的值。

Map 是一种集合,所以我们可以像迭代数组和切片那样迭代它。不过,Map 是无序的,我们无法决定它的返回顺序,这是因为 Map 是使用 hash 表来实现的。

定义 Map

可以使用内建函数 make 也可以使用 map 关键字来定义 Map:

  1. /* 声明变量,默认 map 是 nil */
  2. var map_variable map[key_data_type]value_data_type
  3.  
  4. /* 使用 make 函数 */
  5. map_variable = make(map[key_data_type]value_data_type)

如果不初始化 map,那么就会创建一个 nil map。nil map 不能用来存放键值对

实例

下面实例演示了创建和使用map:

  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6. var countryCapitalMap map[string]string
  7. /* 创建集合 */
  8. countryCapitalMap = make(map[string]string)
  9. /* map 插入 key-value 对,各个国家对应的首都 */
  10. countryCapitalMap["France"] = "Paris"
  11. countryCapitalMap["Italy"] = "Rome"
  12. countryCapitalMap["Japan"] = "Tokyo"
  13. countryCapitalMap["India"] = "New Delhi"
  14. /* 使用 key 输出 map 值 */
  15. for country := range countryCapitalMap {
  16. fmt.Println("Capital of",country,"is",countryCapitalMap[country])
  17. }
  18. /* 查看元素在集合中是否存在 */
  19. captial, ok := countryCapitalMap["United States"]
  20. /* 如果 ok 是 true, 则存在,否则不存在 */
  21. if(ok){
  22. fmt.Println("Capital of United States is", captial)
  23. }else {
  24. fmt.Println("Capital of United States is not present")
  25. }
  26. }

以上实例运行结果为:

  1. Capital of France is Paris
  2. Capital of Italy is Rome
  3. Capital of Japan is Tokyo
  4. Capital of India is New Delhi
  5. Capital of United States is not present

delete() 函数

delete() 函数用于删除集合的元素, 参数为 map 和其对应的 key。实例如下:

  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6. /* 创建 map */
  7. countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
  8. fmt.Println("原始 map")
  9. /* 打印 map */
  10. for country := range countryCapitalMap {
  11. fmt.Println("Capital of",country,"is",countryCapitalMap[country])
  12. }
  13. /* 删除元素 */
  14. delete(countryCapitalMap,"France");
  15. fmt.Println("Entry for France is deleted")
  16. fmt.Println("删除元素后 map")
  17. /* 打印 map */
  18. for country := range countryCapitalMap {
  19. fmt.Println("Capital of",country,"is",countryCapitalMap[country])
  20. }
  21. }

以上实例运行结果为:

  1. 原始 map
  2. Capital of France is Paris
  3. Capital of Italy is Rome
  4. Capital of Japan is Tokyo
  5. Capital of India is New Delhi
  6. Entry for France is deleted
  7. 删除元素后 map
  8. Capital of Italy is Rome
  9. Capital of Japan is Tokyo
  10. Capital of India is New Delhi
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号