Go中的单例实现

Go中的单例实现,go,casting,thread-safety,singleton,Go,Casting,Thread Safety,Singleton,我有一个结构: type cache struct { cap int ttl time.Duration items map[interface{}]*entry heap *ttlHeap lock sync.RWMutex NoReset bool } it实现的接口: type Cache interface { Set(key, value interface{}) bool Get(ke

我有一个结构:

type cache struct {
    cap     int
    ttl     time.Duration
    items   map[interface{}]*entry
    heap    *ttlHeap
    lock    sync.RWMutex
    NoReset bool
}
it实现的接口:

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
}
我不确定哪种类型应该是我的
单例

  • var singleton cache
    时,我无法检查nil


  • 如果
    var singleton Cache
    我无法强制转换为
    singleton.(Cache).lock.lock()
    O获取错误:
    缓存不是类型

  • 如何以正确的方式在Go中写入goroutine安全的单例?

    用于延迟初始化单例值:

    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
    }
    
    用于延迟初始化单例值:

    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
    }
    

    缓存不是一种类型
    ,因为它是函数
    …eton()(cache*cache)…
    的返回参数,这意味着在
    单例
    函数的范围内,您无法访问类型
    缓存
    ,但可以访问类型
    *cache
    的变量
    缓存。另一个问题是,您的逻辑错误,如果singleton不是nil,则返回它,如果它是nil,则尝试对其进行类型断言,这将因为它是nil而导致恐慌。类型断言本身不必惊慌,但.lock。。提示:不建议使用指向接口类型的指针,除非您有一些特殊的要求,需要使用指针。i、 e.我会将
    Singleton()*Cache
    更改为
    Singleton()Cache
    Cache不是一种类型
    ,因为它是函数
    …eton()(Cache*Cache)…
    的返回参数,这意味着在
    Singleton
    函数的作用域中,您无权访问类型
    cache
    ,但可以访问类型
    *cache
    的变量
    cache
    。另一个问题是,您的逻辑是错误的,如果Singleton不是nil,您将返回它,如果它是nil,您将尝试对它进行类型断言,因为它是nil,这将导致死机。类型断言本身不必惊慌,但.lock。。提示:不建议使用指向接口类型的指针,除非您有一些特殊的要求,需要使用指针。i、 e.我会将
    Singleton()*缓存
    更改为
    Singleton()缓存