Go中下划线(空白标识符)的含义 [英] Meaning of underscore (blank identifier) in Go

查看:116
本文介绍了Go中下划线(空白标识符)的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


您可以要求编译器检查类型T是否实现了接口我尝试了一个任务:



  type T struct {} 
var _ I = T {} //验证T实现I.

我不明白_是什么用于和我已经看到它在其他任务,但不明白它的意思。深入挖掘我发现它被称为空白标识符,但我不明白它们的用例:

pre $ code> _ = x //评估x但忽略它

Go成语对我来说仍然感觉有点陌生,所以我试图了解为什么我想要做这样的事情。

>是一个特殊的标识符,你可以指定任何东西但永远不会读取。在第一个示例中,您给出了:

  var _ I = T {} 

没有办法访问这个变量,所以它会被优化出最终的程序。但是,如果类型 T 不能分配给接口 I ,则可能会导致编译错误。所以在这种情况下,它被用作关于类型的静态断言。



第二种情况更常见。虽然扔掉函数调用的结果似乎很奇怪,但在具有多个返回值的函数中它可能更有意义。考虑一个函数 foo ,它返回两个值,但您只对第一个值感兴趣?您可以使用 _ 忽略第二个:

  a,_ = foo()

通过创建另一个变量来保存不需要的返回值,您可以获得相同的效果,但此功能意味着您无需担心为其选择唯一的名称。


As I was reading the Go docs I found this:

You can ask the compiler to check that the type T implements the interface I by attempting an assignment:

type T struct{}
var _ I = T{} // Verify that T implements I.

I don't understand what the _ is used for and I've seen it in other assignments but cannot understand what it means. Digging deeper I found that it's called "blank identifier" but I don't understand the use case they put:

_ = x // evaluate x but ignore it

Go idioms still feel a little alien to me so I'm trying to understand why I would want to do something like this.

解决方案

_ is a special identifier you can assign anything to but never read from. In the first example you gave:

var _ I = T{}

There is no way to access this variable so it will be optimised out of the resulting program. However, it could cause a compile error if the type T is not assignable to the interface I. So in this case it is being used as a static assertion about a type.

The second case is more common. While it might seem strange to throw away the result of a function call, it can make more sense in functions with multiple returns. Consider a function foo that returns two values but you're only interested in the first? You can use _ to ignore the second:

a, _ = foo()

You could get the same effect by creating another variable to hold the unwanted return value, but this feature means you don't need to worry about picking a unique name for it.

这篇关于Go中下划线(空白标识符)的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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