Struct field not updated when implementing interface function

有些话、适合烂在心里 提交于 2019-12-11 08:29:19

问题


If for example we have the following interface:

type IRoute interface {
    AddChildren(child IRoute)
}

The following struct:

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

And implemented the interface:

func (this Route) AddChildren (child globals.IRoute){
    this.Children = append(this.Children, child.(Route))
}

Then in our main func, if we wanted to test this it would not work:

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)

And this does work as expected:

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)

What am I missing? :-)


回答1:


The receiver of func (this Route) AddChildren (child globals.IRoute) is a value, so you are changing a copy of your Route struct.

Change it to func (this *Route) AddChildren (child globals.IRoute)



来源:https://stackoverflow.com/questions/28497254/struct-field-not-updated-when-implementing-interface-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!