参考:https://*.com/questions/59709917/build-a-tree-structure-from-parent-child-pairs-in-go
Firstly, you should never use pointers to slices unless you really have to. It‘s more typical to assign a return value to the variable, e.g. mySlice = sliceReturningFunction()
.
I‘m not sure what all the requirements here are, but one solution could be:
- Build a map of parent-child relations (
map[int][]int
). - Pass the root-level relation to a function that recursively builds the categories.
Here‘s an example recursive function. Note that it returns a new slice rather than mutating a pointer.
func buildCategories(ids []int, relations map[int][]int) []Category {
categories := make([]Category, len(ids))
for i, id := range ids {
c := Category{ID: id}
if childIDs, ok := relations[id]; ok {
c.Child = buildCategories(childIDs, relations)
}
categories[i] = c
}
return categories
}
I added a full example on the Playground. It‘s not tested, and I‘m sure there are better solutions, but it‘s simple and might give you some ideas at least. If you‘re going to have thousands of nodes and this is accessed frequently, you‘re going to need to optimise beyond Go code alone though.
-------------------------------------------------------------------
下面也是一种方法
package main import ( "encoding/json" "fmt" ) type Category struct { ID int `json:"id"` ParentId int `json:"parent_id"` Name string `json:"name"` Url string `json:"url"` Method string `json:"method"` Child []Category `json:"child,omitempty"` } func main() { dataset := [][]int{{1, 0}, {10, 0}, {2, 1}, {3, 1}, {4, 0}, {5, 4}, {6, 4}, {7, 0}, {8, 7}, {9, 2}} // dataset := []Category{{1, 0, "aa", "/ad", "GEt", nil}, {10, 0, "aa", "/ad", "GEt", nil}, {2, 1, "aa", "/ad", "GEt", nil}, {3, 1, "aa", "/ad", "GEt", nil}, // {4, 0, "aa", "/ad", "GEt", nil}, {5, 4, "aa", "/ad", "GEt", nil}, {6, 4, "aa", "/ad", "GEt", nil}, {7, 0, "aa", "/ad", "GEt", nil}, {8, 7, "aa", "/ad", "GEt", nil}, // {9, 2, "aa", "/ad", "GEt", nil}} relations := relationMap(dataset) categories := buildCategories(relations[0], relations) // pass root-level IDs j, _ := json.Marshal(categories) fmt.Println(string(j)) } func relationMap(dataset [][]int) map[int][]int { relations := make(map[int][]int) for _, relation := range dataset { child, parent := relation[0], relation[1] relations[parent] = append(relations[parent], child) } return relations } func buildCategories(ids []int, relations map[int][]int) []Category { categories := make([]Category, len(ids)) for i, id := range ids { c := Category{ID: id} if childIDs, ok := relations[id]; ok { // build child‘s children c.Child = buildCategories(childIDs, relations) } categories[i] = c } return categories }