1 回答

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
切片不是數(shù)組
附加到函數(shù)中的切片不會(huì)增加原始切片的長度和容量。
change := func(slice []int) {
slice = append(slice, 3)
}
slice := []int{1, 2}
change(slice)
fmt.Println(slice)
// Output: [1 2]
無論如何,即使您解決了切片問題,您的輸出也不會(huì)像預(yù)期的那樣。您基本上使用的是樹數(shù)據(jù)結(jié)構(gòu),因此建議使用一些樹搜索算法。這是您使用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
}
- 1 回答
- 0 關(guān)注
- 130 瀏覽
添加回答
舉報(bào)