【Go语言精进之路】构建高效Go程序:了解map实现原理并高效使用
    		       		warning:
    		            这篇文章距离上次修改已过448天,其中的内容可能已经有所变动。
    		        
        		                
                
// 定义一个简单的map
var countryCapitalMap map[string]string
 
func init() {
    countryCapitalMap = make(map[string]string)
    countryCapitalMap["France"] = "Paris"
    countryCapitalMap["Italy"] = "Rome"
    countryCapitalMap["China"] = "Beijing"
    countryCapitalMap["Spain"] = "Madrid"
    countryCapitalMap["USA"] = "Washington D.C."
}
 
// 获取国家的首都
func getCapital(country string) string {
    if capital, ok := countryCapitalMap[country]; ok {
        return capital
    }
    return "Capital not found"
}
 
func main() {
    // 示例使用
    fmt.Println(getCapital("France")) // 输出: Paris
}这段代码首先定义了一个map来存储国家和它们对应的首都,然后初始化了这个map。getCapital函数用于检索指定国家的首都,如果国家存在于map中,则返回对应的首都,否则返回"Capital not found"。在main函数中,我们调用getCapital来获取法国的首都并打印输出。这个例子展示了如何有效地使用map数据结构来存储和检索键值对数据。
评论已关闭