问题
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