Go Tutorial
Go Useful Resources
Selected Reading
- Go - 错误处理
- Go - Interfaces
- Go - 类型转换
- Go - 递归
- Go - Maps
- Go - 范围
- Go - 切片
- Go - 结构
- Go - 指针
- Go - 数组
- Go - 字符串
- Go - 作用域
- Go - 函数
- Go - 循环
- Go - 条件判断
- Go - 操作符
- Go - 常量
- Go - 变量
- Go - 数据类型
- Go - 基本语法
- Go - 程序结构
- Go - 环境设置
- Go - 概述
- Go - Home
Go Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Go - Maps
Go - Maps
Go提供了另一个名为map的重要数据类型,它将唯一的键映射到值。键是一个对象,您可以使用它在以后检索值。给定一个键和一个值,就可以将该值存储在Map对象中。存储值之后,您可以使用其密钥来检索它。
Defining a 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)
Example
以下示例说明了如何创建和使用地图−
package main import "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") } }
When the above code is compiled and executed, it produces the following result −
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() Function
delete()函数用于从映射中删除条目。它需要地图和要删除的相应密钥。例如−
package main import "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]) } }
When the above code is compiled and executed, it produces the following result −
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