Ai
1 Star 1 Fork 1

大滴锦/我常用的的go_func

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
SimpleGenericCache.go 1.50 KB
一键复制 编辑 原始数据 按行查看 历史
大滴锦 提交于 2024-08-30 11:16 +08:00 . 优化泛型缓存
package main
import "sync"
type SimpleGenericCache[K Ordered, V any] struct { // 使用 Ordered
cache map[K]V
mu sync.RWMutex
}
/*简单缓存------------------*/
//对象初始化
func NewSimpleGenericCache[K Ordered, V any]() (*SimpleGenericCache[K, V], error) {
if err := checkGoVersionCanUseGenerics(); err != nil {
return nil, err
}
return &SimpleGenericCache[K, V]{
cache: make(map[K]V),
}, nil
}
// 设置缓存项
func (c *SimpleGenericCache[K, V]) Set(key K, value V) {
c.mu.Lock()
defer c.mu.Unlock()
c.cache[key] = value
}
// 获取缓存项
func (c *SimpleGenericCache[K, V]) Get(key K) (V, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
value, ok := c.cache[key]
return value, ok
}
// 删除某个Key
func (c *SimpleGenericCache[K, V]) Del(key K) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.cache, key)
}
// ShowAllKey 获取所有缓存key
func (c *SimpleGenericCache[K, V]) ShowAllKey() []K {
keys := make([]K, 0)
c.mu.RLock()
defer c.mu.RUnlock()
for key := range c.cache {
keys = append(keys, key)
}
return keys
}
func (c *SimpleGenericCache[K, V]) UnSafeRlock() {
c.mu.RLock()
}
func (c *SimpleGenericCache[K, V]) UnSafeRUnlock() {
c.mu.RUnlock()
}
func (c *SimpleGenericCache[K, V]) UnSafeLock() {
c.mu.Lock()
}
func (c *SimpleGenericCache[K, V]) UnSafeUnLock() {
c.mu.Unlock()
}
func (c *SimpleGenericCache[K, V]) UnSafeGet(key K) (V, bool) {
value, ok := c.cache[key]
return value, ok
}
func (c *SimpleGenericCache[K, V]) UnSafeSet(key K, value V) {
c.cache[key] = value
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dadjin/my-commonly-used-go-func.git
git@gitee.com:dadjin/my-commonly-used-go-func.git
dadjin
my-commonly-used-go-func
我常用的的go_func
v0.1.4

搜索帮助