通过这个例子了解map的使用。
Go语言程序:
// map project main.go
package main
import (
"fmt"
"sort"
)
func main() {
var countryCapitalMap map[string]string
/* 创建集合 */
countryCapitalMap = make(map[string]string)
/* map 插入 key-value 对,各个国家对应的首都 */
countryCapitalMap["France"] = "Paris"
countryCapitalMap["Italy"] = "Rome"
countryCapitalMap["Japan"] = "Tokyo"
countryCapitalMap["India"] = "New Delhi"
countryCapitalMap["China"] = "Beijing"
fmt.Println("Original:")
/* 使用 key 输出 map 值 */
for country := range countryCapitalMap {
fmt.Println("Capital of", country, "is", countryCapitalMap[country])
}
fmt.Println("")
/* map 删除 key-value 对 */
delete(countryCapitalMap, "India")
fmt.Println("After deletion:")
/* 使用 key 输出 map 值 */
for country := range countryCapitalMap {
fmt.Println("Capital of", country, "is", countryCapitalMap[country])
}
fmt.Println("")
/* 映射反转 */
capitalCountryMap := make(map[string]string, len(countryCapitalMap))
for country, capital := range countryCapitalMap {
capitalCountryMap[capital] = country
}
fmt.Println("After the reversal:")
for capital := range capitalCountryMap {
fmt.Println("Country of", capital, "is", capitalCountryMap[capital])
}
fmt.Println("")
/* 查看元素在集合中是否存在 */
captial, ok := countryCapitalMap["United States"]
/* 如果 ok 是 true, 则存在,否则不存在 */
if ok {
fmt.Println("Capital of United States is", captial)
} else {
fmt.Println("Capital of United States is not present")
}
fmt.Println("")
/* 排序输出 */
var keys []string
for k := range countryCapitalMap {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println("Key:", k, "Value:", countryCapitalMap[k])
}
}
程序运行结果:
Original:
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Capital of China is Beijing
After deletion:
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of China is Beijing
After the reversal:
Country of Paris is France
Country of Rome is Italy
Country of Tokyo is Japan
Country of Beijing is China
Capital of United States is not present
Key: China Value: Beijing
Key: France Value: Paris
Key: Italy Value: Rome
Key: Japan Value: Tokyo
程序说明:
1.map似乎可以直接使用
2.排序可以使用sort包
3.map是无序的需要另外定义一个数组来排序
参考链接: