问题描述
type noRows struct{}
var _ Result = noRows{}
我的问题是为什么要初始化一个变量,但立即抛弃它?
My question is why initialize a variable but discard it immediately?
推荐答案
标识符有许多可能的用途,但其主要目的是允许从具有多个回报的函数中丢弃返回:
The blank identifier has many possible uses, but its main purpose is to allow discarding returns from functions that have multiple returns:
// We only care about the rune and possible error, not its length
r, _, err := buf.ReadRune()
还有其他一些好玩的功能,但有时候会使用它。
There are some other fun, but sometimes hackish, uses.
将导入或局部变量标记为used,以便编译器不会发出一个错误:
Mark an import or local variable as "used" so that the compiler won't issue an error:
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
}
确保一个类型实现了一个interfac e在编译时:
Make sure a type implements an interface at compile time:
var _ InterfaceType = Type{} // or new(Type), or whatever
确保一个常量在编译时在一定范围内:
Ensure that a constant lies within a certain range at compile time:
// Ensure constVal <= 10
const _ uint = 10 - constVal
// Ensure constVal >= 1 (constVal > UINT_MAX + 1 is also an error)
const _ uint = -1 + constVal
确保一个函数参数未被使用:
Ensure a function parameter is unused:
// 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 struct {} var _ Result = noRows {}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!