type noRows struct{}
var _ Result = noRows{}
My question is why initialize a variable but discard it immediately?
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.
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 }