开发手册 欢迎您!
软件开发者资料库

Go - Maps

Go Maps - 从简单和简单的步骤学习Go Library,从基本到高级概念,包括概述,环境设置,程序结构,基本语法,数据类型,变量,常量,运算符,决策,循环,函数,范围规则,数组,指针,结构,切片,范围,地图,递归,类型转换,接口,错误处理。

Go提供另一种名为map的重要数据类型,它将唯一键映射到值.键是用于在以后检索值的对象.给定键和值,您可以将值存储在Map对象中.存储该值后,您可以使用其键检索它.

定义地图

您必须使用 make 创建地图的功能.

/* declare a variable, by default map will be nil*/var map_variable map[key_data_type]value_data_type/* define the map as nil map can not be assigned any value*/map_variable = make(map[key_data_type]value_data_type)

示例

以下示例说明如何创建和使用地图 :

package mainimport "fmt"func main() {   var countryCapitalMap map[string]string   /* create a map*/   countryCapitalMap = make(map[string]string)      /* insert key-value pairs in the map*/   countryCapitalMap["France"] = "Paris"   countryCapitalMap["Italy"] = "Rome"   countryCapitalMap["Japan"] = "Tokyo"   countryCapitalMap["India"] = "New Delhi"      /* print map using keys*/   for country := range countryCapitalMap {      fmt.Println("Capital of",country,"is",countryCapitalMap[country])   }      /* test if entry is present in the map or not*/   capital, ok := countryCapitalMap["United States"]      /* if ok is true, entry is present otherwise entry is absent*/   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 DelhiCapital of France is ParisCapital of Italy is RomeCapital of Japan is TokyoCapital of United States is not present

delete()函数

删除( )函数用于从地图中删除条目.它需要地图和要删除的相应密钥.例如 :

package mainimport "fmt"func main() {      /* create a map*/   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}      fmt.Println("Original map")         /* print map */   for country := range countryCapitalMap {      fmt.Println("Capital of",country,"is",countryCapitalMap[country])   }      /* delete an entry */   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 MapCapital of France is ParisCapital of Italy is RomeCapital of Japan is TokyoCapital of India is New DelhiEntry for France is deletedUpdated MapCapital of India is New DelhiCapital of Italy is RomeCapital of Japan is Tokyo