代码地址
https://github.com/fangkang7/goLearn
映射的几种写法
package main import "fmt" func main010() { 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"] fmt.Println("咔咔打印", ok) /* 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") } } func main() { // 映射定义的几种方式 //var scoreMap map[string]int = map[string]int{} //var scoreMap = map[string]int{} //scoreMap := map[string]int{} // 没有指定长度,一开始就是0 scoreMap := make(map[string]string) scoreMap["咔咔博客地址"] = "blog.fangkang.top" scoreMap["咔咔手赚网地址"] = "fangkang.top" // 根据键值访问值 fmt.Println("咔咔博客地址为", scoreMap["咔咔博客地址"]) fmt.Println("咔咔手赚网地址为", scoreMap["咔咔手赚网地址"]) // 修改键值 scoreMap["咔咔手赚网地址"] = "https://fangkang.top" fmt.Println("咔咔手赚网地址", scoreMap["咔咔手赚网地址"]) // 带校验的访问键值 这里的ok返回true 和 false notExist, ok := scoreMap["不存在的键值"] if ok { fmt.Println("存在的啊") } // 关于上边用:= 这里用 = 简单说明一下 上边的定义赋值在一起 下面只是进行赋值 notExist, ok = scoreMap["咔咔博客地址"] if ok { fmt.Println(notExist) } // 访问一个不存在的键 fmt.Println("咔咔手赚网地址", notExist, ok) } /** 对映射进行遍历 */ func main123() { scoreMap := map[string]string{} scoreMap["咔咔博客地址"] = "blog.fangkang.top" scoreMap["咔咔手赚网地址"] = "fangkang.top" // %s 代表的是字符串 for key, value := range scoreMap { fmt.Printf("scoreMap[%s]=%s\n", key, value) } }