登录
首页 >  Golang >  Go问答

传递结构复合体给函数

来源:stackoverflow

时间:2024-03-22 13:51:34 308浏览 收藏

在 Go 中,使用结构组合来实现继承,但将派生结构传递给采用基结构的函数时会出现问题。本文探讨了如何通过将嵌套的基结构作为参数传递来解决此问题。此外,还介绍了一种使用接口来解决此问题的方法,该方法涉及使用反射动态地获取和设置对象的值。

问题内容

需要一些帮助来理解 golang。

来自使用基类的 c++,这是微不足道的。在 go 中,使用结构组合,它工作得很好,直到我需要具有采用“base”结构的函数。我知道它并不是真正的基类,但是当从派生类向基类的字段赋值时,它工作得很好。但我无法将 dog 传递到采用 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
    
}

解决方案


processwolf 函数采用 wolf 参数,因此您必须传递 wolf。由于这两个结构都嵌入了 wolf,因此您可以执行以下操作:

processwolf(porthos.wolf) 
processwolf(aussie.wolf)

因为当您将 wolf 嵌入到 dog 中时,dog 会获取 wolf 拥有的所有方法,加上 dog 有一个名为 wolf 的成员。

当我最初发布我试图简化问题陈述,也许也是如此塞达尔先生很友善地回答了这个问题,但没有帮助解决我的问题。在深入研究 gophers 语言之后,我发现了一个使用 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)

没有 dog 和 dingo 必须与基类相关。但我确实觉得 golang 的设计者做出了一些我至今无法理解的奇怪转变。虽然追逐地鼠很有趣。

终于介绍完啦!小伙伴们,这篇关于《传递结构复合体给函数》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>