Specifications: what is the purpose of an empty identifier when assigning a variable?

I found this variable declaration var _ PropertyLoadSaver = (*Doubler)(nil) , and I wonder what its purpose is. It does not seem to initialize anything, and since it uses an empty identifier, I think you cannot access it.

+5
source share
1 answer

This is a compile-time statement in which the *Doubler type satisfies the PropertyLoadSaver interface.

If the *Doubler type *Doubler not satisfy the interface, compilation will fail 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) evaluates to a value of type *Doubler . *Doubler can only be assigned to a variable of type ProperytLoadSaver if *Doubler implements the PropertyLoadSaver interface.

The empty identifier _ is used because the variable does not need a link elsewhere in the package. The same result can be achieved using a non-empty identifier:

 var assertStarDoublerIsPropertyLoadSaver PropertyLoadSaver = (*Doubler)(nil) 
+8
source

All Articles