Go语言入门之Map详解
    		       		warning:
    		            这篇文章距离上次修改已过441天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "fmt"
)
 
func main() {
    // 声明map
    var countryCapitalMap map[string]string
 
    // 创建map
    countryCapitalMap = make(map[string]string)
 
    // 添加键值对
    countryCapitalMap["China"] = "Beijing"
    countryCapitalMap["India"] = "New Delhi"
    countryCapitalMap["USA"] = "Washington D.C."
    countryCapitalMap["Indonesia"] = "Jakarta"
 
    // 查看map的长度
    fmt.Println("Length of map:", len(countryCapitalMap))
 
    // 遍历map
    for country := range countryCapitalMap {
        fmt.Printf("Capital of %s is %s\n", country, countryCapitalMap[country])
    }
 
    // 删除键值对
    delete(countryCapitalMap, "Indonesia")
 
    // 查看map的长度
    fmt.Println("Length of map after deleting Indonesia:", len(countryCapitalMap))
 
    // 查看特定国家的首都
    fmt.Println("Capital of USA is:", countryCapitalMap["USA"])
}这段代码首先声明了一个字符串到字符串的映射,然后创建了这个映射,并添加了一些键值对。接着,它展示了如何遍历映射,删除一个键值对,查看映射的长度,并查询特定键对应的值。这个例子展示了Go语言中map的基本操作,是学习Go语言的一个很好的起点。
评论已关闭