关键字 var 后面的下划线和接口名是什么意思?

来自 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行,代码运行良好。

21228 次浏览

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.

It seems like you are creating a dummy value of type ValueConverter, assigning a new boolType object to it and then discarding it (which is the meaning of the underscore in go, as in for _, elt := range myRange { ...} if you are not interested in the index of the enumeration).

My guess is that it simply correspond to a static check to ensure that the struct boolType does implement the ValueConverter interface. This way, when you change the implementation of boolType, the compiler will complain early if you broke the implementation of ValueConverter interface as it will be unable to cast your new boolType to this interface.