2018-09-05 18:34:41 +08:00
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
2019-04-03 00:03:46 +08:00
|
|
|
|
"fmt"
|
2019-07-29 21:01:19 +08:00
|
|
|
|
|
|
|
|
|
"github.com/gogf/gf/container/gmap"
|
2018-09-05 18:34:41 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func main() {
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 创建一个默认的gmap对象,
|
2019-09-01 22:22:08 +08:00
|
|
|
|
// 默认情况下该gmap对象不支持并发安全特性,
|
2019-11-27 23:19:07 +08:00
|
|
|
|
// 初始化时可以给定true参数开启并发安全特性,用以并发安全场景。
|
2019-04-03 00:03:46 +08:00
|
|
|
|
m := gmap.New()
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 设置键值对
|
|
|
|
|
for i := 0; i < 10; i++ {
|
|
|
|
|
m.Set(i, i)
|
|
|
|
|
}
|
|
|
|
|
// 查询大小
|
|
|
|
|
fmt.Println(m.Size())
|
|
|
|
|
// 批量设置键值对(不同的数据类型对象参数不同)
|
2019-05-11 20:47:25 +08:00
|
|
|
|
m.Sets(map[interface{}]interface{}{
|
2019-04-03 00:03:46 +08:00
|
|
|
|
10: 10,
|
|
|
|
|
11: 11,
|
|
|
|
|
})
|
|
|
|
|
fmt.Println(m.Size())
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 查询是否存在
|
|
|
|
|
fmt.Println(m.Contains(1))
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 查询键值
|
|
|
|
|
fmt.Println(m.Get(1))
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 删除数据项
|
|
|
|
|
m.Remove(9)
|
|
|
|
|
fmt.Println(m.Size())
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 批量删除
|
2019-05-11 20:47:25 +08:00
|
|
|
|
m.Removes([]interface{}{10, 11})
|
2019-04-03 00:03:46 +08:00
|
|
|
|
fmt.Println(m.Size())
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 当前键名列表(随机排序)
|
|
|
|
|
fmt.Println(m.Keys())
|
|
|
|
|
// 当前键值列表(随机排序)
|
|
|
|
|
fmt.Println(m.Values())
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 查询键名,当键值不存在时,写入给定的默认值
|
2019-05-11 20:47:25 +08:00
|
|
|
|
fmt.Println(m.GetOrSet(100, 100))
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 删除键值对,并返回对应的键值
|
2019-05-11 20:47:25 +08:00
|
|
|
|
fmt.Println(m.Remove(100))
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 遍历map
|
|
|
|
|
m.Iterator(func(k interface{}, v interface{}) bool {
|
|
|
|
|
fmt.Printf("%v:%v ", k, v)
|
|
|
|
|
return true
|
|
|
|
|
})
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 自定义写锁操作
|
|
|
|
|
m.LockFunc(func(m map[interface{}]interface{}) {
|
|
|
|
|
m[99] = 99
|
|
|
|
|
})
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 自定义读锁操作
|
|
|
|
|
m.RLockFunc(func(m map[interface{}]interface{}) {
|
|
|
|
|
fmt.Println(m[99])
|
|
|
|
|
})
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 清空map
|
|
|
|
|
m.Clear()
|
2018-09-05 18:34:41 +08:00
|
|
|
|
|
2019-04-03 00:03:46 +08:00
|
|
|
|
// 判断map是否为空
|
|
|
|
|
fmt.Println(m.IsEmpty())
|
2018-09-05 18:34:41 +08:00
|
|
|
|
}
|