type noRows struct{}
var _ Result = noRows{}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么初始化变量但立即丢弃它?
空白标识符有许多可能的用途,但其主要目的是允许从具有多个返回的函数中丢弃返回:
// We only care about the rune and possible error, not its length
r, _, err := buf.ReadRune()
Run Code Online (Sandbox Code Playgroud)
还有其他一些乐趣,但有时是hackish,用途.
将导入或本地变量标记为"已使用",以便编译器不会发出错误:
import "fmt"
var _ = fmt.Println // now fmt is used and the compiler won't complain
func main() {
var x int
_ = x // now x is used and the compiler won't complain
}
Run Code Online (Sandbox Code Playgroud)
确保类型在编译时实现接口:
var _ InterfaceType = Type{} // or new(Type), or whatever
Run Code Online (Sandbox Code Playgroud)
确保在编译时常量位于某个范围内:
// Ensure constVal <= 10
const _ uint = 10 - constVal
// Ensure constVal >= 1 (constVal > UINT_MAX + 1 is also an error)
const _ uint = -1 + constVal
Run Code Online (Sandbox Code Playgroud)
确保未使用函数参数:
// This could be useful if somebody wants a value of type
// func(int, int) int
// but you don't want the second parameter.
func identity(x, _ int) int { return x }
Run Code Online (Sandbox Code Playgroud)