Go语言映射
Go编程提供另一个重要的数据类型是映射,唯一映射一个键到一个值。一个键要使用在以后检索值的对象。给定的键和值,可以在一个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 main import "fmt" func main { var coutryCapitalMap map[string]string /* create a map*/ coutryCapitalMap = 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*/ captial, 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 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()函数是用于从映射中删除一个项目。映射和相应的键将被删除。下面是一个例子:
package main import "fmt" func main { /* create a map*/ coutryCapitalMap := 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 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