Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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.

like image 698
The user with no hat Avatar asked Jul 03 '16 06:07

The user with no hat


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)
like image 197
Bayta Darell Avatar answered Oct 24 '22 11:10

Bayta Darell