1

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 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Happy I could help. Here is a little further reading: golang.org/doc/faq#Pointers and for this specific question golang.org/doc/faq#methods_on_values_or_pointers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.