Interfaces satisfying interfaces
Shannon
Posted on January 13, 2022
<< this post is mostly just a refresher for myself >>
Interfaces are often confusing for me. When I started parsing through some of the core/v1 kubernetes code, something stuck out to me: there are a lot of interfaces in here. Some only needing a single method to be satisfied.
Within this, a common theme was interfaces satisfying interfaces. This is a weak point of mine, so I crafted up a quick example to jog my memory.
Here's the code:
func main(){
var a nested
c := cat{}
a = c
a.Speak()
d := dog{}
a = d
a.Speak()
}
type nested interface {
random
}
type random interface {
animal
}
type animal interface {
Speak()
}
type cat struct{}
type dog struct{}
func (c cat) Speak() {
fmt.Println("meow")
}
func (d dog) Speak() {
fmt.Println("woof")
}
As you can see, there are three interfaces here: nested
, random
, and animal
. However, only one of these has an actual method attached to it: animal
. The other 2 are simply requiring other interfaces to be satisfied.
From there, I set up two object types, cat
and dog
, which both have the Speak()
method. As you can see, it just prints out a statement.
Once in the main
function, I set up a nested
variable, which is an interface. This interface only requires an object that satisfies random
which requires animal
which requires any object type that has a method Speak()
. In this case, bot the cat and dog objects do.
From there, I set the a
variable to a dog or cat variable and call the methods.
This, however, will not work if we try to call a.Speak()
before assigning an object that satisfies all of these conditions. If, for instance, I had the below code:
func main(){
var a nested
a.Speak()
}
It would cause a panic because the interface is currently <nil>
.
Anyways, it was a good refresher on interfaces within Go for myself :)
Posted on January 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.