我有一个缓存对象的接口,它lru从以下镜像缓存github.com/hashicorp/golang-lru:
type Cacher interface {
Add(key, value interface{})
Get(key interface{}) (value interface{}, ok bool)
}
在main.go满足某些条件时创建对象,否则它保持为空:
import lru "github.com/hashicorp/golang-lru"
...
var cache *lru.ARCCache
if someCondition {
cache, _ = lru.NewARC(int(cacheSize))
}
... later on
r.Cache = cache
现在,在另一个包中,我在对其进行任何操作之前检查缓存是否为零:
if r.Cache != nil {
v, found := r.Cache.Get(...)
}
这会导致invalid memory address or nil pointer dereference 错误,因为类型不是 nil 但值是。
我的问题是如何检查是否r.Cache为 nil 而不必github.com/hashicorp/golang-lru在该包中导入(这使得使用Cacher接口毫无意义):if r.Cache != (*lru.ARCCache)(nil)
暮色呼如
HUWWW
相关分类