3
type noRows struct{}

var _ Result = noRows{}

私の質問は、なぜ変数を初期化するのにすぐに破棄するのかということです。</ p>

4

2 に答える 2

7

空白の識別子には多くの用途がありますが、その主な目的は、複数の戻り値を持つ関数からの戻り値を破棄できるようにすることです。

// 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 }
于 2012-10-11T21:02:32.067 に答える
3

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.

于 2012-10-11T15:31:11.023 に答える