Specs: What’s the purpose of the blank identifier in variable assignment? [duplicate]

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)

Leave a Comment