无涯教程-Go - Maps(映射)

34 阅读1分钟

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

定义映射

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

/* 声明一个变量,默认情况下 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

参考链接

www.learnfk.com/go/go-maps.…