更新时间:2022-10-19 14:09:31
_
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.