将结构复合传递到函数中

需要一些帮助来理解golang。


来自使用基类C++这是微不足道的。在 Go 中,使用结构组合,它工作正常,直到我需要具有采用“Base”结构的功能。我知道它不是真正的基类,但是当涉及到从派生的基类的字段分配值时,它工作正常。但是我不能传递到一个采取.DogWolf


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

    

}


qq_花开花谢_0
浏览 137回答 2
2回答

炎炎设计

该函数采用参数,因此您必须传递 .由于这两种结构都嵌入在其中,因此您可以执行以下操作:processWolfWolfWolfWolfprocessWolf(porthos.Wolf)&nbsp;processWolf(aussie.Wolf)&nbsp;因为当你嵌入到 ,得到所有的方法都有,加上有一个名为 的成员。WolfDogDogWolfDogWolf

ITMISS

当我最初发布问题时,我试图简化问题陈述,也许太多了,Serdar先生很好心地回答了这个问题,但没有帮助我的问题。在深入研究了gophers的lang之后,我遇到了一个使用interface{}来解决这个问题的解决方案。我改编了我的mongo代码,它正在工作,尽管我可能会说它看起来不像其他语言传递引用那么简单。// FindAll retrieves one object from the collectionfunc FindAll(collection *mongo.Collection, filter bson.M, resultSet interface{}) error {&nbsp; &nbsp; ctx, cancel := context.WithTimeout(context.Background(), 30*time.Seconds)&nbsp; &nbsp; defer cancel()&nbsp; &nbsp; cursor, err := collection.Find(ctx, filter)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; defer cursor.Close(ctx)&nbsp; &nbsp; objects := reflect.ValueOf(resultSet).Elem()&nbsp; &nbsp; for cursor.Next(ctx) {&nbsp; &nbsp; &nbsp; &nbsp; obj := reflect.New(objects.Type().Elem())&nbsp; &nbsp; &nbsp; &nbsp; err = cursor.Decode(obj.Interface())&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Panicln("FindAll:", err.Error())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // assuming that an interface is out of alignment and need to know ASAP.&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; objects = reflect.Append(objects, obj.Elem())&nbsp; &nbsp; }&nbsp; &nbsp; reflect.ValueOf(resultSet).Elem().Set(objects)&nbsp; &nbsp; return nil}然后调用它使用&nbsp; &nbsp; var dogs []Dog&nbsp; &nbsp; if err := database.FindAll(houseCollection, bson.M{}, &dogs); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; println(dogs)&nbsp; &nbsp; var dingos []Dingo&nbsp; &nbsp; if err := database.FindAll(houseCollection, bson.M{}, &dingos); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; println(dingos)没有狗和野狗必须与基类相关。但我真的觉得Golang的设计师做了一些奇怪的转折,我还没有理解。虽然有乐趣追逐地鼠。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go