我有一個緩存對象的接口,它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.ARCCacheif someCondition { cache, _ = lru.NewARC(int(cacheSize))}... later onr.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)
2 回答

暮色呼如
TA貢獻1853條經驗 獲得超9個贊
避免檢查接口中的 nil 具體值,因為 nil 值可能是接口的有效實現。這是一個有點人為的例子,說明 nil 有效的地方:
type exampleCacher struct { }
func (c *exampleCacher) Get(key interface{}) (value interface{}, ok bool) }
if c == nil {
return nil, false
}
...
}
解決此問題的更好方法是確保代碼僅將有效值分配給r.Cache.
問題中的代碼始終設置r.Cache為非零值,因為代碼將具體類型分配給r.Cache. 有關解釋,請參閱關于 nil 錯誤的常見問題解答條目。
通過聲明cache為Cacher.
var cache Cacher
正如我在上面的評論中提到的,另一個解決方法是:
if cache != nil {
r.Cache = cache
}

HUWWW
TA貢獻1874條經驗 獲得超12個贊
請注意(*lru.ARCCache)(nil) != Cacher(nil)。
所以不要分配(*lru.ARCCache)(nil)給r.Cache.
這是修復:
if cache != nil {
r.Cache = cache
}
- 2 回答
- 0 關注
- 142 瀏覽
添加回答
舉報
0/150
提交
取消