type noRows struct{}
var _ Result = noRows{}
我的问题是为什么初始化一个变量却立即丢弃它?</p>
空白标识符有许多可能的用途,但其主要目的是允许丢弃来自具有多个返回的函数的返回:
// We only care about the rune and possible error, not its length
r, _, err := buf.ReadRune()
还有其他一些有趣的,但有时是骇人听闻的用途。
将导入或局部变量标记为“已使用”,以便编译器不会发出错误:
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
}
确保一个类型在编译时实现了一个接口:
var _ InterfaceType = Type{} // or new(Type), or whatever
确保一个常量在编译时位于某个范围内:
// Ensure constVal <= 10
const _ uint = 10 - constVal
// Ensure constVal >= 1 (constVal > UINT_MAX + 1 is also an error)
const _ uint = -1 + constVal
确保未使用函数参数:
// 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 }
有些人使用类似的线作为接口检查。这一行确保该类型noRows
实现了Result
接口。如果不是,您将收到编译器错误。
我相信这样的检查是不必要的。通常,任何涉及该类型的测试都会告诉您何时类型不满足重要接口。在极少数情况下,您可以在单元测试中添加转换测试。