Sorting by slice fields

前端 未结 1 1223
温柔的废话
温柔的废话 2020-12-11 19:33

I have the following Structs:

type Parent struct {
    id       string
    children []Child
}

type Child struct {
    id string
}

I have m

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 19:56

    I got it to work using the following code:

    // sort each Parent in the parents slice by Id
    sort.Slice(parents, func(i, j int) bool {return parents[i].id < parents[j].id})
    
    // for each Parent, sort each Child in the children slice by Id
    for _, parent := range parents {
        sort.Slice(parent.children, func(i, j int) bool {return parent.children[i].id < parent.children[j].id})
    }
    

    Special thanks to @Volker for mentioning the sort.Slice function! I had no idea it existed!

    0 讨论(0)
提交回复
热议问题