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

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

问题描述

我发现这个变量声明 var _ PropertyLoadSaver =(* Doubler)(nil) ,我想知道它的目的是什么。它似乎没有初始化任何东西,因为它使用了一个空白的标识符,我猜你不能访问它。

解决方案

是一个编译时断言, * Doubler 类型满足 PropertyLoadSaver 接口。
$ b 如果 * Doubler 类型不满足该接口,则编译将退出,其错误类似于:

  prog.go:21:不能在类型PropertyLoadSaver中使用(* Doubler)(nil)(type * Doubler):
* Doubler未实现PropertyLoadSaver(缺少Save方法)

以下是它的工作原理。代码 var _ PropertyLoadSaver 声明了一个 PropertyLoadSaver 类型的未命名变量。表达式(* Doubler)(nil)的计算结果为 * Doubler 类型的值。 * Doubler 只能分配给类型 ProperytLoadSaver 的变量,如果 * Doubler 实现 PropertyLoadSaver 接口。



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

  var assertStarDoublerIsPropertyLoadSaver 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.

解决方案

This is a compile time assertion that *Doubler type satisfies the PropertyLoadSaver interface.

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)

Here's how it works. The code var _ PropertyLoadSaver declares an unnamed variable of type PropertyLoadSaver. The expression (*Doubler)(nil) evaluates to a value of type *Doubler. The *Doubler can only be assigned to the variable of type ProperytLoadSaver 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天全站免登陆