我有一个结构:
type cache struct {
cap int
ttl time.Duration
items map[interface{}]*entry
heap *ttlHeap
lock sync.RWMutex
NoReset bool
}
它实现的接口:
type Cache interface {
Set(key, value interface{}) bool
Get(key interface{}) (interface{}, bool)
Keys() []interface{}
Len() int
Cap() int
Purge()
Del(key interface{}) bool
}
函数返回单例:
func Singleton() (cache *Cache) {
if singleton != nil {
return &singleton
}
//default
singleton.(cache).lock.Lock()
defer singleton.(cache).lock.Unlock()
c := New(10000, WithTTL(10000 * 100))
return &c
}
我不确定哪种类型应该是我的singleton
:
var singleton cache
我不能检查零var singleton Cache
我不能施放到singleton.(cache).lock.Lock()
O得到错误:cache is not a type
如何以正确的方式在Go中编写goroutine-safe Singleton?
使用sync.Once懒惰地初始化单例值:
var (
singleton Cache
once sync.Once
)
func Singleton() Cache {
once.Do(func() {
singleton = New(10000, WithTTL(10000*100))
})
return singleton
}
如果可以在程序启动时初始化,那么执行以下操作:
var singleton Cache = New(10000, WithTTL(10000*100))
func Singleton() Cache {
return singleton
}