Interface 实现接口功能时未更新结构字段

Interface 实现接口功能时未更新结构字段,interface,go,Interface,Go,例如,如果我们有以下接口: type IRoute interface { AddChildren(child IRoute) } func (this Route) AddChildren (child globals.IRoute){ this.Children = append(this.Children, child.(Route)) } 以下结构: type Route struct { Alias string `json:"alias"` Chi

例如,如果我们有以下接口:

type IRoute interface {
    AddChildren(child IRoute)
}
func (this Route) AddChildren (child globals.IRoute){
    this.Children = append(this.Children, child.(Route))
}
以下结构:

type Route struct {
    Alias string `json:"alias"`
    Children []Route `json:"children,omitempty"`
    Url string `json:"url,omitempty"`
}
并实现了接口:

type IRoute interface {
    AddChildren(child IRoute)
}
func (this Route) AddChildren (child globals.IRoute){
    this.Children = append(this.Children, child.(Route))
}
然后在我们的主要功能中,如果我们想测试它,它将不起作用:

rSettings := Route{"settings", nil, "/admin/settings"}
rSettingsContentTypesNew := models.Route{"new", nil, "/new?type&parent"}
rSettingsContentTypesEdit := models.Route{"edit", nil, "/edit/:nodeId"}

// Does NOT work - no children is added
rSettingsContentTypes.AddChildren(rSettingsContentTypesNew)
rSettingsContentTypes.AddChildren(rSettingsContentTypesEdit)
rSettings.AddChildren(rSettingsContentTypes)
这确实如预期的那样起作用:

rSettings := Route{"settings", nil, "/admin/settings"}
rSettingsContentTypesNew := models.Route{"new", nil, "/new?type&parent"}
rSettingsContentTypesEdit := models.Route{"edit", nil, "/edit/:nodeId"}

// However this does indeed work
rSettingsContentTypes.Children = append(rSettingsContentTypes.Children,rSettingsContentTypesNew)
rSettingsContentTypes.Children = append(rSettingsContentTypes.Children,rSettingsContentTypesEdit)
rSettings.Children = append(rSettings.Children,rSettingsContentTypes)

我错过了什么?:-)

func(此路由)AddChildren(child globals.IRoute)的接收者是一个值,因此您正在更改
路由
结构的副本


将其更改为
func(this*Route)AddChildren(child globals.IRoute)

func(this Route)AddChildren(child globals.IRoute)
的接收者是一个值,因此您正在更改
路由
结构的副本


将其更改为
func(this*Route)AddChildren(child globals.IRoute)

很高兴我能帮忙。这里有一点进一步的阅读:对于这个具体的问题,我很高兴能提供帮助。这里有一点进一步的阅读:对于这个具体的问题