我有這個結構(注意它是遞歸的?。簍ype Group struct { Name string Item []string Groups []Group}我想將一個字符串附加到Item深埋在 Group 數組的層次結構中的數組中。關于這個新項目的路徑,我所掌握的唯一信息是它所在組的名稱。假設路徑是“foo/bar/far”。我想修改 bar 而不覆蓋 foo、bar 或“root”數組。基本上,我想編寫一個函數,返回一個新的 Group 變量,該變量與原始變量相同,但附加了新字符串。到目前為止我已經嘗試過以下方法:循環遍歷包含路徑的所有組名稱的數組,如果它們位于當前組中,則將當前組變量設置為該新組。循環完成后,將字符串附加到數組并返回當前組。當然,唯一的問題是根組的其余部分被刪除并替換為新的、修改過的組。代碼: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}
1 回答

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
我想您可以將組作為指針傳遞給 addItem 函數,并忽略該函數的返回值
有一點像
func addItem(list *Group, newItem string, path string) Group {
? ? var currentGroup *Group = list
? ? if path == "" {
? ? ? ? currentGroup.Item = append(currentGroup.Item, newItem)
? ? } else {
? ? ? ? for _, elem := range strings.Split(path, "/") {
? ? ? ? ? ? in, index := in(elem, currentGroup.Groups)
? ? ? ? ? ? if in {
? ? ? ? ? ? ? ? currentGroup = ¤tGroup.Groups[index]
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? currentGroup.Item = append(currentGroup.Item, newItem)
? ? }
? ? return *currentGroup
}
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報
0/150
提交
取消