在下面的代碼中,我有一個低級模塊RelationshipBrowser定義了一個FindAllChildrenOf方法,我有一個結構Relationships,它的屬性relations是一個片斷,另一個結構名為Research,作為屬性browser。我為Relationships宣告了一個接收函式FindAllChildrenOf,為Research宣告了另一個接收函式Investigate,我想我的問題是。當我在函式Investigate中實作邏輯時,它顯然是在呼叫瀏覽器介面來觸發函式FindAllChildrenOf,并自動去知道我所指的是Relationship型別。我的困惑是,在這種情況下,RelationshipBrowser和Relationship是如何連接的,而它們似乎沒有任何聯系?
const (
父關系=iota
兒童
姊妹關系
)
type Person struct {
名稱 字串
}
type Info struct{
來自*人
關聯關系
到*人
}
//低級別的模塊。
type RelationshipBrowser interface{
FindAllChildrenOf(name string) []*Person
}
type Relationships struct{
關系[]資訊
}
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.relation{
if v.relatiionship == Parent && v.from.name==name{
result = append(result, r.relations[i].to)
}
}
return result
}
//高級別模塊
type Research struct{
// break DIP
//關系 Relationships
瀏覽器 RelationshipBrowser
}
func (r *Research)Investigate(){
// relations:= r.relationship.relationship
// for _, rel := range relations{
// if rel.from.name == "John" && rel.relatiionship == Parent{
// fmt.Println("John有一個孩子叫", rel.to.name)
// }
// }
children:=r.browser.FindAllChildrenOf("John"/span>)
for _,child:=range children{
fmt.Println("John有一個孩子叫", child.name)
}
}
func main(){
parent:= Person{"John"}。
child1:= Person{"Chris"}。
child2:= Person{"Matt"}。
relationships:= Relationships{}
relationships.AddParentAndChild(&parent,&child1)
relationships.AddParentAndChild(&parent,&child2)
r :=研究{&關系}。
r.Investigate()
}
uj5u.com熱心網友回復:
go自動知道我指的是關系型別。
是的,因為Go知道RelationshipBrowser的確切地址,所以如果它愿意,它可以知道一切。 你也可以知道一切,通過反射,見https://go.dev/blog/laws-of-reflection
在你的代碼中,你在這里明確地傳遞了地址:
r := Research{&relations}
RelationshipBrowser和Relationships通過這個地址連接在一起,因為Research認為它是一個RelationshipBrowser,但它實際上是一個Relationships。
uj5u.com熱心網友回復:
我剛剛發現,通過呼叫r.Investigate,程式知道我是指Relationship結構。我仍然是一個圍棋初學者,所以學習曲線很深。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/313121.html
標籤:
下一篇:使用cout后,物件陣列被破壞了
