douyin8623 2015-03-06 14:33
浏览 15
已采纳

去递归添加项目到数组不起作用

I have been doing some golang programming and usually has been lot of fun. Now I have this code I need to port from C# to go and it is just not working. The idea is to fill a tree of employees from database but inner slices are not being filled up on each call. Better to write the code here

func (db *DalBase) TitleAllChildren(tx *gorp.Transaction) (items []Title, err error) {
    var dbChildren []entities.Title
    _, err = tx.Select(&dbChildren, "select * from title where idparent is null order by name")
    if err != nil {
        return
    }

    items = make([]Title, 0)
    for i := range dbChildren {
        currItem := &dbChildren[i]
        item := &Title{Id: currItem.Id, Name: currItem.Name}
        err = db.TitleChildrenRecursive(tx, item)
        if err != nil {
            return
        }
        items = append(items, *item)
    }
    return
}

func (db *DalBase) TitleChildrenRecursive(tx *gorp.Transaction, u *Title) (err error) {
    var dbChildren []entities.Title
    _, err = tx.Select(&dbChildren, "select * from title where idparent = $1 order by name", u.Id)
    if err != nil {
        return
    }

    if len(dbChildren) != 0 {
        u.Items = make([]Title, 0)
        for i := range dbChildren {
            currItem := &dbChildren[i]
            item := &Title{Id: currItem.Id, Name: currItem.Name}
            err = db.TitleChildrenRecursive(tx, item)
            if err != nil {
                return
            }
            u.Items = append(item.Items, *item)
        }
    }

    return
}

I have logged the values on each recursive call and they are being filled inside the function, but when it bubbles up to the parent, slices are empty.

I wouldn't like to use pointers to slices, is it possible to implement?

Edit: here is the struct I am trying to fill

type Title struct {
    Id    string  `json:"id"`
    Name  string  `json:"name"`
    Items []Title `json:"items"`
}
  • 写回答

1条回答 默认 最新

  • duanci1858 2015-03-06 18:03
    关注

    You won't need a pointer to a slice, as long you are passing around a pointer to the struct which contains your slice.

    Each time you call TitleChildrenRecursive, you're replacing your slice with a new one before anything is appended:

    u.Items = make([]Title, 0)
    

    There's no need to make a new slice, since append works correctly with a nil slice.

    You should also change []Title to []*Title, so that if any append operations happen to children items after they are added to the slice, it's reflected throughout the tree.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?