Meaning of underscore (blank identifier) in Go

This is common in languages that allow multiple return values. There are situations where you don't actually care about one of the return values.

For example, in Go, it is common to return an error. If for some reason you don't care about that error, you can choose to ignore it:

value, _ := methodThatReturnsValueAndError()

If however, you assign it and don't use it, there is a compiler error:

value, err := methodThatReturnsValueAndError()
// if you don't use "err" .. its an error

_ is a special identifier you can assign anything to but never read from. In the first example you gave:

var _ I = T{}

There is no way to access this variable so it will be optimised out of the resulting program. However, it could cause a compile error if the type T is not assignable to the interface I. So in this case it is being used as a static assertion about a type.

The second case is more common. While it might seem strange to throw away the result of a function call, it can make more sense in functions with multiple returns. Consider a function foo that returns two values but you're only interested in the first? You can use _ to ignore the second:

a, _ = foo()

You could get the same effect by creating another variable to hold the unwanted return value, but this feature means you don't need to worry about picking a unique name for it.

Tags:

Go