Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

go - 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
    
}
question from:https://stackoverflow.com/questions/65649114/passing-struct-composites-into-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...