GO map类型
发布日期:2021-06-30 15:37:03 浏览次数:2 分类:技术文章

本文共 1874 字,大约阅读时间需要 6 分钟。

package mainimport (   "fmt"   "sort"   "sync")func main() {   //map 是引用类型,可以使用如下方式声明:   //var mapname map[keytype]valuetype   //Go语言中 map 是一种特殊的数据结构,一种元素对(pair)的无序集合,   // pair 对应一个 key(索引)和一个 value(值),所以这个结构也称为关联数组或字典,   // 这是一种能够快速寻找值的理想结构,给定 key,就可以迅速找到对应的 value。   //map 这种数据结构在其他编程语言中也称为字典(Python)、hash 和 HashTable 等。   var mapList map[string]int   mapList = map[string]int{"int": 1, "one": 1}   fmt.Printf("Map literal at \"one\" is: %d\n", mapList["one"])   fmt.Println(mapList["one"])   //创建方式mapCreated := make(map[string]float)等价于mapCreated := map[string]float{} 。   //map的容量   //与数组不同,map可以根据新增的key-value 动态的伸缩因此它不存在固定的长度或最大的限制   //,但是也可以选择标明 map 的初始容量 capacity   //格式:make(map[keytype]valuetype, cap)   map2 := make(map[string]int, 10)   fmt.Println(map2)   //用切片作为map的值   mp1 := make(map[int][]int)   mp2 := make(map[int]*[]int)   fmt.Println(mp1)   fmt.Println(mp2)   //map 遍历   scene := make(map[string]int)   scene["name"] = 123   scene["exe"] = 1234432   for k, v := range scene {      fmt.Println(k, "=》", v)   }   //把 map数据遍历到切片中   var sceneList []int   for _, v := range scene {      sceneList = append(sceneList, v)   }   fmt.Println(sort.IntSlice(sceneList))   //删除和清空map delete(map, 键)   delete(scene, "name")   for k, v := range scene {      fmt.Println(k, "=》", v)   }   //Sync.Map 在并发中使用的map   //go在并发情况下 只读是线程是安全的 同时读写是线程不安全的   //sync.Map 不能使用 map 的方式进行取值和设置等操作,   // 而是使用 sync.Map 的方法进行调用,Store 表示存储,Load 表示获取,Delete 表示删除。   var scene_1 sync.Map   //将键值保存到sync中   scene_1.Store("greece", 97)   scene_1.Store("key", 98)   //从 sync中取值   fmt.Println(scene_1.Load("key"))   //根据key删除值   //scene_1.Delete("key")   //遍历   scene_1.Range(func(key, value interface{}) bool {      fmt.Println(key, value)      return true   })   //sync.Map 没有提供获取 map 数量的方法,替代方法是在获取 sync.Map 时遍历自行计算数量,   // sync.Map 为了保证并发安全有一些性能损失,因此在非并发情况下,使用 map 相比使用 sync.Map 会有更好的性能}

转载地址:https://jsonll.blog.csdn.net/article/details/103512538 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:go 函数的定义
下一篇:golang 数组与切片分析

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月18日 04时38分34秒