I have the following code to organise *Widget
structs into a hierarchy. Parent()
returns the widget with an ID of the caller's parentID. The hierarchy can be up to 4 or 5 levels deep.
type Widget struct {
ID int64
ParentID int64
}
func (w *Widget) Parent() *Widget {
// Returns the widget with an ID of w.ParentID
}
What I want to achieve is a function which aggregates the parent, as well as the parent's parent etc. to the top of the hierarchy, and returns a slice of all of the parent IDs. As I don't know the depth of the hierarchy, I think I need some sort of programmatic recursion to get the parent of each parent, which would do something like the following:
func (w *Widget) AllParents() []*Widget {
var parentWidgets []*Widget
x := w.Parent()
parentWidgets = append(parentWidgets, x)
y := x.Parent()
parentWidgets = append(parentWidgets, y)
...
return parentWidgets
}
Is there a more idiomatic way of achieving this?