sync.Map 有以下特性:
- 无须初始化,直接声明即可。
- sync.Map 不能使用 map 的方式进行取值和设置等操作,而是使用 sync.Map 的方法进行调用,Store 表示存储,Load 表示获取,Delete 表示删除。
- 使用 Range 配合一个回调函数进行遍历操作,通过回调函数返回内部遍历出来的值,Range 参数中回调函数的返回值在需要继续迭代遍历时,返回 true,终止迭代遍历时,返回 false。
简单的使用栗子
func syncMapDemo() {
var smp sync.Map
// 数据写入
smp.Store("name", "小红")
smp.Store("age", 18)
// 数据读取
name, _ := smp.Load("name")
fmt.Println(name)
age, _ := smp.Load("age")
fmt.Println(age)
// 遍历
smp.Range(func(key, value interface{
}) bool {
fmt.Println(key, value)
return true
})
// 删除
smp.Delete("age")
age, ok := smp.Load("age")
fmt.Println("删除后的查询")
fmt.Println(age, ok)
// 读取或写入,存在就读取,不存在就写入
smp.LoadOrStore("age", 100)
age, _ = smp.Load("age")
fmt.Println("不存在")
fmt.Println(age)
smp.LoadOrStore("age", 99)
age, _ = smp.Load("age")
fmt.Println("存在")
fmt.Println(age)
}