go - client-go 中的 golang 语法
问题描述
有人可以帮我理解这些代码吗?
在 client-go 项目中,有一些我无法理解的代码。代码路径是 \tols\cache\store.go
Add(obj interface{}) error
Update(obj interface{}) error
Delete(obj interface{}) error
List() []interface{}
ListKeys() []string
Get(obj interface{}) (item interface{}, exists bool, err error)
GetByKey(key string) (item interface{}, exists bool, err error)
// Replace will delete the contents of the store, using instead the
// given list. Store takes ownership of the list, you should not reference
// it after calling this function.
Replace([]interface{}, string) error
Resync() error
}
type cache struct {
// cacheStorage bears the burden of thread safety for the cache
cacheStorage ThreadSafeStore
// keyFunc is used to make the key for objects stored in and retrieved from items, and
// should be deterministic.
keyFunc KeyFunc
}
var _ Store = &cache{}
最后一行“var_Store = &cache{}”,这是什么意思,有官方文档支持吗?
解决方案
在 golang 中,如果定义了一个变量并且不使用它,那么它会报错。通过_
用作名称,您可以克服这一点。我想每个人都已经_, err := doSomething()
在 golang 中看到过。var _ Store = &cache{}
与此没有什么不同。这里最棒的Store
是一个接口,所以通过这样做var _ Store = &cache{}
,它强制caches
实现接口Store
。如果caches
不实现接口,您的代码将无法编译。这是何等绝妙的招数?
推荐阅读
- javascript - 电子邮件和密码不会通过美国传递到 firebase
- sql - 将年数和月数转换为月数
- android - BroadcastReceiver Android 中的 locationManager.requestLocationUpdates
- bash - 为什么在这个 git hook 示例的末尾使用 exec(似乎没有必要)?
- objective-c - 从 URLSession 传递 NSError 的正确方法
- php - PHP Preg 替换。删除 {~ string ~} 模式内的字符串,但跳过
{~字符串~}
- javascript - 在 Javascript 中创建循环以与 imap-simple nodejs 包一起使用
- git - 2个分支之间的Git差异仅显示功能分支中所做的更改
- mysql - 使用临时表数据填充一组变量
- javascript - 导出和导入函数,没有错误,但得到'...不是从...导出的'