type noRows struct{} var _ Result = noRows{}

huangapple go评论78阅读模式
英文:

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 &quot;fmt&quot;

var _ = fmt.Println // now fmt is used and the compiler won&#39;t complain

func main() {
    var x int
    _ = x // now x is used and the compiler won&#39;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 &lt;= 10
const _ uint = 10 - constVal
// Ensure constVal &gt;= 1 (constVal &gt; 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&#39;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.

huangapple
  • 本文由 发表于 2012年10月11日 23:24:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/12843132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定