规格:变量赋值中的空白标识符的目的是什么? [英] Specs: What's the purpose of the blank identifier in variable assignment?

查看:31
本文介绍了规格:变量赋值中的空白标识符的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这个变量声明 var _PropertyLoadSaver = (*Doubler)(nil) 我想知道它的目的是什么.它似乎没有初始化任何东西,因为它使用了一个空白标识符,我猜你无法访问它.

I've found this variable declaration var _ PropertyLoadSaver = (*Doubler)(nil) and I'm wondering what's its purpose. It doesn't seem to initialise anything and as it uses a blank identifier I guess you can't access it.

推荐答案

这是*Doubler 类型满足PropertyLoadSaver 接口的编译时断言.当该类型的方法集是该类型的方法集的超集时,该类型实现了一个接口界面.

This is a compile time assertion that *Doubler type satisfies the PropertyLoadSaver interface. A type implements an interface when the method set for the type is a superset of the method set for the interface.

如果*Doubler类型不满足接口,则编译会退出,报错类似:

If the *Doubler type does not satisify the interface, then compilation will exit with an error similar to:

prog.go:21: cannot use (*Doubler)(nil) (type *Doubler) as type PropertyLoadSaver in assignment:
*Doubler does not implement PropertyLoadSaver (missing Save method)

这是它的工作原理.代码var _ PropertyLoadSaver 声明了一个类型为PropertyLoadSaver 的未命名变量.表达式 (*Doubler)(nil) 转换无类型的 nil到 *Doubler 类型的 nil 值.*Doubler 只能分配给 PropertyLoadSaver 类型的变量,前提是 *Doubler 实现了 PropertyLoadSaver 接口.

Here's how it works. The code var _ PropertyLoadSaver declares an unnamed variable of type PropertyLoadSaver. The expression (*Doubler)(nil) converts the untyped nil to a nil value of type *Doubler. The *Doubler can only be assigned to the variable of type PropertyLoadSaver if *Doubler implements the PropertyLoadSaver interface.

使用空白标识符 _ 是因为不需要在包的其他地方引用该变量.使用非空标识符可以实现相同的结果:

The blank identifier _ is used because the variable does not need to be referenced elsewhere in the package. The same result can be achieved with a non-blank identifier:

var assertStarDoublerIsPropertyLoadSaver PropertyLoadSaver = (*Doubler)(nil)

这篇关于规格:变量赋值中的空白标识符的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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