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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With