登录
首页 >  Golang >  Go问答

golang中实现下层模块和上层模块的通信

来源:stackoverflow

时间:2024-02-21 10:12:20 387浏览 收藏

大家好,我们又见面了啊~本文《golang中实现下层模块和上层模块的通信》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

在下面的代码中,我有一个较低级别的模块 relationshipbrowser 定义了 findallchildrenof 方法,并且我有一个结构 relationships ,它具有属性 relations ,它是一个切片,另一个名为 research 的结构作为属性 browser。我为 relationships 声明了一个接收器函数 findallchildrenof ,为 research 声明了另一个接收器函数 investigate ,我想我的问题是,当我在函数 investigate 中实现逻辑时,它显然是在调用浏览器接口来触发函数 z qbczqbfindallchildrenof 并自动知道我指的是输入 relationship。我的困惑是,relationshipbrowser 和relationships 在这种情况下如何连接,而它们似乎没有连接?

const (
    Parent Relationship = iota
    Child
    Sibiling
)

type Person struct {
    name string
}

type Info struct{
    from *Person
    relatiionship Relationship
    to *Person
}

// low-level module
type RelationshipBrowser interface{
    FindAllChildrenOf(name string)[]*Person
    
}

type Relationships struct{
    relations []Info
}

func (r *Relationships)AddParentAndChild(parent,child *Person){
        r.relations = append(r.relations, Info{parent,Parent,child})
        r.relations = append(r.relations, Info{child,Child,parent})
    }

func (r *Relationships)FindAllChildrenOf(name string)[]*Person{
    result:= make([]*Person,0)
    for i,v:= range r.relations{
        if v.relatiionship == Parent && v.from.name==name{
            result = append(result, r.relations[i].to)
        }     
    }
    return result
}
// high-level module



type Research struct{
// break DIP
    // relationships Relationships 
    browser RelationshipBrowser
}

func (r *Research)Investigate(){
    // relations:= r.relationships.relations
    // for _, rel := range relations{
    //  if rel.from.name == "John" && rel.relatiionship == Parent{
    //      fmt.Println("John has a child called", rel.to.name)
    //  }
    // }
        children:=r.browser.FindAllChildrenOf("John")
        for _,child:=range children{
            fmt.Println("John has a child called", child.name)
        }

}

func main(){
    parent:= Person{"John"}
    child1:= Person{"Chris"}
    child2:= Person{"Matt"}
    relationships:= Relationships{}
    relationships.AddParentAndChild(&parent,&child1)
    relationships.AddParentAndChild(&parent,&child2)
    r := Research{&relationships}
    r.Investigate()

}

正确答案


是的,因为 go 知道 relationshipbrowser 的确切地址,所以如果它愿意的话它可以知道一切。 你也可以知道一切,通过反思,见https://go.dev/blog/laws-of-reflection

在您的代码中,您在此处明确传递地址:

r := Research{&relationships}

relationshipbrowser 和relationships 通过此地址连接在一起,因为研究将其视为relationshipbrowser,但它实际上是一个relationships。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《golang中实现下层模块和上层模块的通信》文章吧,也可关注golang学习网公众号了解相关技术文章。

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