Anonymous interfaces
April 13, 2023
Today we pick up the second half of an example we started with yesterday:
Similarly, consider this interface specification, which appears within a type declaration to define an interface called Locker:
type Locker interface { Lock() Unlock() }
If
S1
andS2
also implementfunc (p T) Lock() { … } func (p T) Unlock() { … }
they implement the
Locker
interface as well as theFile
interface.
We’ve already discussed that a single type may automatically satisfy multiple interfaces, so there’s not much to add here.
What I would like to elaborate on, though, is that an interface type doesn’t necissarily have to be named, as it is in this example. Anonymous interfaces are entirely usable as well. Let’s look at an example, building on the above code.
This code references the above Locker
type in a type assertion, to see whether variable x
implements the Locker
interface, and if so, calls Lock()
on the variable.
if locker, ok := x.(Locker); ok {
locker.Lock()
}
We can do the same without explicitly declaring that Locker
type, though:
if locker, ok := x.(interface{ Lock() }); ok {
locker.Lock()
}
Here we inline the interface declaration anonymously (I’ve also omitted the Unlock()
method, since I’m not calling it in the example.)
Quotes from The Go Programming Language Specification Version of December 15, 2022