Go - 地图



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

定义映射

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


/* 声明一个变量,默认情况下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
	 	/* create a map*/
	 	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 中删除条目。它需要 map 和要删除的相应 key。例如 -


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") 		
	 	
	 	/* 打印地图 */
	 	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