
https://github.com/fangkang7/golearn
映射的几种写法第一种一站式声明赋值
countryCAPItalMap := make(map[string]string) 第二种先声明在赋值
var countryCAPItalMap map[string]string countryCAPItalMap = make(map[string]string) 第三种
var countryCAPItalMap map[string]string = make(map[string]string) 第四种
// 创建一个映射,使用字符串切片作为值myMap := map[int][]string{} 案例 注意点 在以上案例中有一行这代码,这个是把映射里边的值赋值给ok 当映射里存在这个值时为true 反之为fales
代码
package mainimport "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) }} 博主微信欢迎交流 总结 以上是内存溢出为你收集整理的【GO】复合类型:映射全部内容,希望文章能够帮你解决【GO】复合类型:映射所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)