实现接口函数时,Struct字段未更新

时间:2015-02-13 10:17:55

标签: interface go

例如,如果我们有以下界面:

type IRoute interface {
    AddChildren(child IRoute)
}

以下结构:

type Route struct {
    Alias string `json:"alias"`
    Children []Route `json:"children,omitempty"`
    Url string `json:"url,omitempty"`
}

并实施了界面:

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)

我错过了什么? : - )

1 个答案:

答案 0 :(得分:5)

func (this Route) AddChildren (child globals.IRoute)的接收方是一个值,因此您要更改Route结构的副本。

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