if-statement - 使用接口时检查变量类型是否为零
问题描述
我有一个缓存对象的接口,它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)
解决方案
避免检查接口中的 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
}
推荐阅读
- angular - 用于保存数据的 Angular 调用服务
- c++ - 如何旋转向量的特定子集?
- qt - 如何通过多级子线程保持 GUI 平稳运行
- python - Scipy b 样条基函数
- python - Matplotlib 图例不适用于三元散点图
- wordpress - 在 wordpress 页面模板中访问 Vue 应用程序中的字体资源
- django - 试图在模型中将 slug 添加到 get_absolute_url 函数的末尾(Django)
- amazon-web-services - 创建k8s资源并等待它完成继续下一个
- iterator - 如何动态组合生成器?
- python - python FIFO股票投资组合计算