Go - Maps(映射)

Go - Maps(映射) 首页 / Golang入门教程 / Go - Maps(映射)

Go提供了另一个重要的数据类型,称为map,它将唯一键映射到值,键(key)是一个对象 ,您可以在以后使用它来检索值。

定义映射

您必须使用 make 函数来创建Map映射。

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/go/go-maps.html

来源:LearnFk无涯教程网

/* 声明一个变量,默认情况下 map 将为 nil */
var map_variable map[key_data_type]value_data_type

/* 将地图定义为 nil 地图不能分配任何值 */
map_variable=make(map[key_data_type]value_data_type)

映射示例

package main

import "fmt"

func main() {
   var countryCapitalMap map[string]string
   /* 创建映射 */
   countryCapitalMap=make(map[string]string)
   
   /* 在映射中插入键值对*/
   countryCapitalMap["France"]="Paris"
   countryCapitalMap["Italy"]="Rome"
   countryCapitalMap["Japan"]="Tokyo"
   countryCapitalMap["India"]="New Delhi"
   
   /* 使用键打印映射 */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* 测试映射中是否存在条目*/
   capital, ok := countryCapitalMap["United States"]
   
   /* 如果 ok 为真,则存在条目,否则不存在条目*/
   if(ok){
      fmt.Println("Capital of United States is", capital)  
   } else {
      fmt.Println("Capital of United States is not present") 
   }
}

编译并执行上述代码后,将产生以下输出-

Capital of India is New Delhi
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of United States is not present

delete()函数

delete()函数用于从Map映射中删除条目。如-

package main

import "fmt"

func main() {   
   /* 创建映射 */
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
   
   fmt.Println("Original map")   
   
   /* 打印映射 */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* 删除元素 */
   delete(countryCapitalMap,"France");
   fmt.Println("Entry for France is deleted")  
   
   fmt.Println("Updated map")   
   
   /* print map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
}

编译并执行上述代码后,将产生以下输出-

Original Map
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry for France is deleted
Updated Map
Capital of India is New Delhi
Capital of Italy is Rome
Capital of Japan is Tokyo

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入剖析Kubernetes -〔张磊〕

编辑训练营 -〔总编室〕

深入浅出云计算 -〔何恺铎〕

实用密码学 -〔范学雷〕

说透数字化转型 -〔付晓岩〕

如何成为学习高手 -〔高冷冷〕

搞定音频技术 -〔冯建元 〕

深入C语言和程序运行原理 -〔于航〕

深入浅出分布式技术原理 -〔陈现麟〕

好记忆不如烂笔头。留下您的足迹吧 :)