Search code examples
goinheritancecomposition

Passing struct composites into function


Need some help understanding golang.

Coming from C++ using a base class this is trivial. In Go, using struct composition, which works fine up to the point where I need to have function that take the "Base" struct. I understand that it's not truly a base class, but when comes to assigning values to the fields of the base class from the derived, it works fine. But I cannot pass Dog into a function that takes Wolf.

package main
    
import "fmt"
    
type Wolf struct {
    ID     string
    Schema int
}
    
type Dog struct {
    Wolf
}
    
type Dingo struct {
    Wolf
}
    
func processWolf(wolf Wolf) {
    fmt.Println(wolf.ID, wolf.Schema)
}
    
func main() {
    porthos := Dog{}
    porthos.ID = "Porthos"  // works fine able to set field of Wolf
    porthos.Schema = 1      // works fine
    
    aussie := Dingo{}
    aussie.ID = "Aussie"  // works fine
    aussie.Schema = 1     // works fine
    
    fmt.Println(porthos.ID, porthos.Schema)
    fmt.Println(aussie.ID, aussie.Schema)

    processWolf(porthos) << fails here
    processWolf(aussie) << fails here
    
}

Solution

  • The processWolf function takes a Wolf argument, so you have to pass a Wolf. Since both structures have Wolf embedded in them, you can do:

    processWolf(porthos.Wolf) 
    processWolf(aussie.Wolf) 
    

    because when you embed Wolf into Dog, Dog gets all the methods Wolf has, plus Dog has a member called Wolf.