关键字 var 后的下划线和接口名称是什么意思? [英] What does an underscore and interface name after keyword var mean?
问题描述
来自 http://golang.org/src/pkg/database/sql/driver/types.go:
type ValueConverter interface {
// ConvertValue converts a value to a driver Value.
ConvertValue(v interface{}) (Value, error)
}
var Bool boolType
type boolType struct{}
var _ ValueConverter = boolType{} // line 58
func (boolType) String() string { return "Bool" }
func (boolType) ConvertValue(src interface{}) (Value, error) {....}
我知道 ValueConverter 是一个接口名称.第 58 行似乎声明了 boolType 实现了接口 ValueConverter,但这有必要吗?我删除了第 58 行,代码运行良好.
I known that ValueConverter is an interface name. Line 58 seems to declare that boolType implement interface ValueConverter, but is that necessary? I deleted line 58 and the code works well.
推荐答案
它提供了一个静态(编译时)检查 boolType
是否满足 ValueConverter
接口.用作变量名称的 _
告诉编译器有效地丢弃 RHS 值,但对其进行类型检查并评估它是否有任何副作用,但匿名变量本身并没有不占用任何进程空间.
It provides a static (compile time) check that boolType
satisfies the ValueConverter
interface. The _
used as a name of the variable tells the compiler to effectively discard the RHS value, but to type-check it and evaluate it if it has any side effects, but the anonymous variable per se doesn't take any process space.
在开发和接口的方法集和/或类型实现的方法经常更改时,这是一个方便的构造.该构造可防止忘记匹配旨在使它们兼容的类型和接口的方法集.它有效地防止了去安装
一个有这种遗漏的损坏(中间)版本.
It is a handy construct when developing and the method set of an interface and/or the methods implemented by a type are frequently changed. The construct serves as a guard against forgetting to match the method sets of a type and of an interface where the intent is to have them compatible. It effectively prevents to go install
a broken (intermediate) version with such omission.
这篇关于关键字 var 后的下划线和接口名称是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!