Home > Back-end >  Retrieve a slice of IDs recursively in GO
Retrieve a slice of IDs recursively in GO

Time:09-07

type MenuItem struct {
        Id              int32       
        Type            string           
        SortOrder       int8        
        CategoryId      int32   
        Children        []*MenuItem 
    }

If you have this struct, and you have a slice of []MenuItem. I would like to retrieve a slice only with CategoryId values. This looks like a recursive use case due to the Children but based on how append function for slices works, it looks a bit tricky. Any ideas? How would you do it?

The end result should be a slice of []int32: [11, 1900, 12, 1300,...., 2090]

CodePudding user response:

Let append do the hard work for you, handling memory expansion, and return its result during each recursive step:

func traverse(m *MenuItem) (r []int32) {

    if m == nil {
        return
    }

    r = append(r, m.CategoryId)

    for _, c := range m.Children {
        r = append(r, traverse(c)...)
    }

    return
}

https://go.dev/play/p/8d0cyPMV0r6

  • Related