亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何編輯隱藏在遞歸結構中的數組

如何編輯隱藏在遞歸結構中的數組

Go
夢里花落0921 2023-07-10 10:55:55
我有這個結構(注意它是遞歸的?。簍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 = &currentGroup.Groups[index]

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? currentGroup.Item = append(currentGroup.Item, newItem)

? ? }


? ? return *currentGroup

}

查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號