I have an interface RootInterface
embedded in a struct OneConcrete
. This concrete implementation of the interface is then embedded into another struct TwoConcrete
as RootInterface
again.
How do I determine that the actual implementation of RootInterface
is OneConcrete
? The following code hopefully shows what I am trying to achieve:
http://play.golang.org/p/YrwDRwQzDc
package main
import "fmt"
type RootInterface interface {
GetInt() int
}
type OneConcrete struct {
}
func (oc OneConcrete) GetInt() int {
return 1
}
type TwoConcrete struct {
RootInterface
}
func main() {
one := OneConcrete{}
fmt.Println("One", one.GetInt())
two := RootInterface(TwoConcrete{RootInterface: one})
_, ok := two.(TwoConcrete)
fmt.Println(ok) // prints true
// How can I get the equivalent of ok == true,
// i.e. find out that OneConcrete is the acutal
// RootInterface implementation?
_, ok = two.(OneConcrete)
fmt.Println(ok) // prints false
}
Note that I would like an answer to the general case where RootInterface
could be embedded arbitrarily deeply within a struct hierarchy.
OneConcrete
does not embeds interface. It implements that interface. Embedding a type mean that struct will get one additional field with same name as given type and all methods of that type will become methods of struct. So, to get OneConcrete
you should do two.(TwoConcrete).RootInterface.(OneConcrete)
.