亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將結構復合傳遞到函數中

將結構復合傳遞到函數中

Go
qq_花開花謝_0 2022-08-01 15:28:31
需要一些幫助來理解golang。來自使用基類C++這是微不足道的。在 Go 中,使用結構組合,它工作正常,直到我需要具有采用“Base”結構的功能。我知道它不是真正的基類,但是當涉及到從派生的基類的字段分配值時,它工作正常。但是我不能傳遞到一個采取.DogWolfpackage 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    }
查看完整描述

2 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

該函數采用參數,因此您必須傳遞 .由于這兩種結構都嵌入在其中,因此您可以執行以下操作:processWolfWolfWolfWolf


processWolf(porthos.Wolf) 

processWolf(aussie.Wolf) 

因為當你嵌入到 ,得到所有的方法都有,加上有一個名為 的成員。WolfDogDogWolfDogWolf


查看完整回答
反對 回復 2022-08-01
?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

當我最初發布問題時,我試圖簡化問題陳述,也許太多了,Serdar先生很好心地回答了這個問題,但沒有幫助我的問題。在深入研究了gophers的lang之后,我遇到了一個使用interface{}來解決這個問題的解決方案。我改編了我的mongo代碼,它正在工作,盡管我可能會說它看起來不像其他語言傳遞引用那么簡單。


// FindAll retrieves one object from the collection

func FindAll(collection *mongo.Collection, filter bson.M, resultSet interface{}) error {


    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Seconds)

    defer cancel()


    cursor, err := collection.Find(ctx, filter)

    if err != nil {

        return err

    }


    defer cursor.Close(ctx)


    objects := reflect.ValueOf(resultSet).Elem()


    for cursor.Next(ctx) {


        obj := reflect.New(objects.Type().Elem())


        err = cursor.Decode(obj.Interface())


        if err != nil {

            log.Panicln("FindAll:", err.Error())

            // assuming that an interface is out of alignment and need to know ASAP.

        }


        objects = reflect.Append(objects, obj.Elem())

    }


    reflect.ValueOf(resultSet).Elem().Set(objects)


    return nil

}

然后調用它使用


    var dogs []Dog

    if err := database.FindAll(houseCollection, bson.M{}, &dogs); err != nil {

        return nil, err

    }


    println(dogs)

    var dingos []Dingo

    if err := database.FindAll(houseCollection, bson.M{}, &dingos); err != nil {

        return nil, err

    }


    println(dingos)

沒有狗和野狗必須與基類相關。但我真的覺得Golang的設計師做了一些奇怪的轉折,我還沒有理解。雖然有樂趣追逐地鼠。


查看完整回答
反對 回復 2022-08-01
  • 2 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號