Specs: What's the purpose of the blank identif

2019-01-06 22:00发布

问题:

This question already has an answer here:

  • What does an underscore and interface name after keyword var mean? 2 answers

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.

回答1:

This is a compile time assertion that *Doubler type satisfies the PropertyLoadSaver 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) evaluates to a value of type *Doubler. The *Doubler can only be assigned to the variable of type ProperytLoadSaver 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)


标签: go