I have this struct (notice that it is recursive!):
type Group struct {
Name string
Item []string
Groups []Group
}
And I want to append a string to the Item
array that is buried deep in the hierarchy of the Group array. The only information I have about the path of this new item is the names of the groups that it's in. Let's say the path is "foo/bar/far". I want to modify bar without overwriting foo, bar or the "root" array. Basically, I want to write a function that returns a new Group variable that is identical to the original variable but with the new string appended.
So far I've tried the following method:
Looping through an array that contains all the group names of the path and if they are in the current group set a current group variable to that new group. Once the loop has finished, append the string to the array and return current group. The only problem is, of course, that the rest of the root group is deleted and replaced with the new, modified group.
The code:
func in(item string, array []Group) (bool, int) {
for i, elem := range array {
if item == elem.Name {
return true, i
} else {
continue
}
}
return false, 0
}
func addItem(list Group, newItem string, path string) Group {
var currentGroup Group = list
if path == "" {
currentGroup.Items = append(currentGroup.Items, newItem)
} else {
for _, elem := range strings.Split(path, "/") {
in, index := in(elem, currentGroup.Groups)
if in {
currentGroup = currentGroup.Groups[index]
}
}
currentGroup.Items = append(currentGroup.Items, newItem)
}
return currentGroup
}