9.7 Go语言入门(映射 Map)
package main
import (
"fmt"
)
func main() {
// 创建一个空的map
countryCapitalMap := make(map[string]string)
// 添加键值对
countryCapitalMap["France"] = "Paris"
countryCapitalMap["Italy"] = "Rome"
countryCapitalMap["India"] = "New Delhi"
countryCapitalMap["China"] = "Beijing"
// 查看map的长度
fmt.Println("Length of map:", len(countryCapitalMap))
// 查看元素是否存在,使用delete函数删除元素
if capital, ok := countryCapitalMap["China"]; ok {
fmt.Printf("Capital of China is %s\n", capital)
} else {
fmt.Println("Capital of China is not present in the map")
}
// 删除元素
delete(countryCapitalMap, "France")
// 遍历map
for country, capital := range countryCapitalMap {
fmt.Printf("Country: %s, Capital: %s\n", country, capital)
}
}
这段代码展示了如何在Go语言中创建和使用map,包括添加元素、检索元素、检查元素是否存在、删除元素以及遍历map。
评论已关闭