登录
首页 >  Golang >  Go问答

Golang:使用id和父id在线性数组中构建嵌套结构

来源:stackoverflow

时间:2024-02-25 09:09:24 479浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《Golang:使用id和父id在线性数组中构建嵌套结构》,涉及到,有需要的可以收藏一下

问题内容

我有一个数据线性名称,例如:

  • 名称:1,id:1,parentid:0
  • 名称:一对一,id:2,parentid:1
  • 名称:一一一,id:3,parentid:2
  • 名称:一一二,id:4,parentid:2

例如,我从数据库中获取此数据,但我认为为了测试逻辑,我将虚拟数据设置为结构。 我想我为数据递归地创建了一个临时索引。如果地图中不存在数据,则设置,如果数据必须附加到切片之前,则获取索引。但是,我认为在函数递归中(我在下面展示),它不起作用(数据不附加)。为什么? 算法逻辑有错误吗?

对于我的结果来说,正确的解决方案是什么

[
  {
    "id": 1,
    "name": "one",
    "children": [
      {
        "id": 2,
        "name": "one-one",
        "children": [
          {
            "id": 3,
            "name": "one-one-one",
            "children": null
          },
          {
            "id": 4,
            "name": "one-one-two",
            "children": null
          }
        ]
      }
    ]
  }
]

golang 中的完整代码:

package main

import (
    "encoding/json"
    "fmt"
)

type Data struct {
    Id       int    `json:"id"`
    ParentId int    `json:"parent_id"`
    Name     string `json:"name"`
}

type Datas []Data

type Response struct {
    Id       int       `json:"id"`
    Name     string    `json:"name"`
    Children Responses `json:"children"`
}

type Responses []*Response

func main() {
    datas := Datas{
        {
            Name: "One",
            Id:   1,
        },
        {
            Name:     "One-One",
            Id:       2,
            ParentId: 1,
        },
        {
            Name:     "One-One-One",
            Id:       3,
            ParentId: 2,
        },
        {
            Name:     "One-One-Two",
            Id:       4,
            ParentId: 2,
        },
    }

    var result Responses
    tempIdx := make(map[int]int)

    for _, val := range datas {
        res := Response{
            Id:   val.Id,
            Name: val.Name,
        }

        if val.ParentId == 0 {
            result = append(result, &res)
            tempIdx[val.Id] = len(result) - 1
            continue
        } else {
            recursive(val.ParentId, result, res, tempIdx)
        }

    }

    json, err := json.Marshal(result)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(json))
}

func recursive(idxParent int, datas Responses, res Response, tempIdx map[int]int) {
    idxData, ok := tempIdx[idxParent]
    if ok {
        // don't work in this "datas[idxData].Children", why?
        recursive(idxData, datas[idxData].Children, res, tempIdx)
    } else {
        datas = append(datas, &res)
        tempIdx[res.Id] = len(datas) - 1
    }
}

使用golang演示打开


正确答案


切片不是数组

附加到函数中的切片不会增加原始切片的长度和容量。

change := func(slice []int) {
    slice = append(slice, 3)
}
slice := []int{1, 2}
change(slice)
fmt.println(slice) 
// output: [1 2]

无论如何即使您解决了切片问题,您的输出也不会达到预期的效果。您基本上使用的是树数据结构,因此建议使用一些树搜索算法。这是您使用 BFS 的工作示例

package main

import (
    "encoding/json"
    "fmt"
)

type Data struct {
    Id       int    `json:"id"`
    ParentId int    `json:"parent_id"`
    Name     string `json:"name"`
}

type Datas []Data

type Response struct {
    Id       int       `json:"id"`
    Name     string    `json:"name"`
    Children Responses `json:"children"`
}

type Responses []*Response

func main() {
    datas := Datas{
        {
            Name: "One",
            Id:   1,
        },
        {
            Name:     "One-One",
            Id:       2,
            ParentId: 1,
        },
        {
            Name:     "One-One-One",
            Id:       3,
            ParentId: 2,
        },
        {
            Name:     "One-One-Two",
            Id:       4,
            ParentId: 2,
        },
    }

    var result Responses
    for _, val := range datas {
        res := &Response{
            Id:   val.Id,
            Name: val.Name,
        }

        var found bool

        // iterate trough root nodes
        for _, root := range result {
            parent := findById(root, val.ParentId)
            if parent != nil {
                parent.Children = append(parent.Children, res)

                found = true
                break
            }
        }

        if !found {
            result = append(result, res)
        }
    }

    out, err := json.Marshal(result)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(out))
}

func findById(root *Response, id int) *Response {
    queue := make([]*Response, 0)
    queue = append(queue, root)
    for len(queue) > 0 {
        nextUp := queue[0]
        queue = queue[1:]
        if nextUp.Id == id {
            return nextUp
        }
        if len(nextUp.Children) > 0 {
            for _, child := range nextUp.Children {
                queue = append(queue, child)
            }
        }
    }
    return nil
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Golang:使用id和父id在线性数组中构建嵌套结构》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>