A
accessing B
reminds me of a is-a relationship, where A
"is-a" B
.
The article "Is Go an Object Oriented language?" does note that there is no true subtyping in Go:
- if it was truly subtyping then the anonymous field would cause the outer type to become the inner type. In Go this is simply not the case. The two types remain distinct.
- The anonymous fields are still accessible as if they were embedded
Example:
package main
type A struct{
// doesn't know anything about B
}
type B struct {
A //B is-a A
}
func (a *A) f() { fmt.Println("A.f") }
func (b *B) f() { fmt.Println("B.f") }
func save(A) {
//do something
}
func main() {
b := B
save(&b) //OOOPS! b IS NOT A
b.f() // B.f()
b.A.f() // A.f()
}
One of the issues with multiple inheritance is that languages are often non obvious and sometimes even ambiguous as to which methods are used when identical methods exist on more than one parent class.
With Go you can always access the individual methods through a property which has the same name as the type.
In reality when you are using Anonymous fields, Go is creating an accessor with the same name as your type.
That is what "b.A
" is: an accessor to an anonymous field..