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()函数用于从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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)