I've found this variable declaration var _ PropertyLoadSaver = (*Doubler)(nil)
and I'm wondering what's its purpose. It doesn't seem to initialise anything and as it uses a blank identifier I guess you can't access it.

- 10,166
- 20
- 57
- 80
1 Answers
This is a compile time assertion that *Doubler
type satisfies the PropertyLoadSaver
interface. A type implements an interface when the method set for the type is a superset of the method set for the interface.
If the *Doubler
type does not satisify the interface, then compilation will exit with an error similar to:
prog.go:21: cannot use (*Doubler)(nil) (type *Doubler) as type PropertyLoadSaver in assignment:
*Doubler does not implement PropertyLoadSaver (missing Save method)
Here's how it works. The code var _ PropertyLoadSaver
declares an unnamed variable of type PropertyLoadSaver
. The expression (*Doubler)(nil)
converts the untyped nil to a nil value of type *Doubler
. The *Doubler
can only be assigned to the variable of type PropertyLoadSaver
if *Doubler
implements the PropertyLoadSaver
interface.
The blank identifier _
is used because the variable does not need to be referenced elsewhere in the package. The same result can be achieved with a non-blank identifier:
var assertStarDoublerIsPropertyLoadSaver PropertyLoadSaver = (*Doubler)(nil)

- 113,709
- 12
- 249
- 242
-
Can you provide a ref to the spec? https://golang.org/ref/spec – The user with no hat Jul 03 '16 at 06:45
-
@Theuserwithnohat it's not in the spec. It's an unofficial convention. – Endophage Jul 03 '16 at 06:50
-
1@Karrot Kake now I understand how it works. It's a kind of trick. As the blank identifiers are not used in any way I guess it produces no garbage, right? off-topic: ``(*Doubler)(nil) `` is nice though. I was not familiar with this either. – The user with no hat Jul 03 '16 at 06:51
-
1The blank identifier is used because the program does not need to reference the variable. A non-blank identifier will produce the same amount of garbage as the blank identifier (which is none). – Charlie Tumahai Jul 03 '16 at 06:57