英文:
type noRows struct{} var _ Result = noRows{}
问题
为什么要初始化一个变量然后立即丢弃它?
英文:
type noRows struct{}
var _ Result = noRows{}
My question is why initialize a variable but discard it immediately?
答案1
得分: 7
空白标识符有许多可能的用途,但其主要目的是允许丢弃具有多个返回值的函数的返回值:
// 我们只关心 rune 和可能的错误,而不关心其长度
r, _, err := buf.ReadRune()
还有一些其他有趣但有时候有些狡猾的用法。
将导入或局部变量标记为“已使用”,以便编译器不会发出错误:
import "fmt"
var _ = fmt.Println // 现在 fmt 被使用了,编译器不会抱怨
func main() {
var x int
_ = x // 现在 x 被使用了,编译器不会抱怨
}
确保类型在编译时实现了一个接口:
var _ InterfaceType = Type{} // 或者 new(Type),或者其他任何东西
确保常量在编译时位于某个范围内:
// 确保 constVal <= 10
const _ uint = 10 - constVal
// 确保 constVal >= 1(constVal > UINT_MAX + 1 也是一个错误)
const _ uint = -1 + constVal
确保函数参数未使用:
// 如果有人想要一个类型为 func(int, int) int 的值,但你不想要第二个参数,这可能会有用。
func identity(x, _ int) int { return x }
英文:
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.
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
}
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 }
答案2
得分: 3
有些人使用这样的一行代码作为接口检查。这行代码确保类型noRows
实现了Result
接口。如果没有实现,你将会得到一个编译错误。
我认为这样的检查是不必要的。通常,任何涉及到该类型的测试都会告诉你当一个类型不满足重要接口时。在非常罕见的情况下,你可以在单元测试中添加一个转换测试。
英文:
Some people use a line like as an interface check. This line ensures that the type noRows
implements the Result
interface. If it doesn't you will get a compiler error.
I believe checks like that are unnecessary. Normally any type of test involving that type will tell you when a type does not satisfy and important interface. In very rare cases, you can add a conversion test to your unit tests.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论