关键字var后的下划线和接口名称是什么意思? [英] What does an underscore and interface name after keyword var mean?

查看:85
本文介绍了关键字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行,代码运行良好.

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.

在开发中并且接口的方法集和/或由类型实现的方法经常更改时,这是一个方便的构造.该构造可以防止忘记匹配类型和接口的方法集,以使它们兼容.这样可以有效地避免将go install这样的遗漏(中间)版本遗漏掉.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆