Golang:按切片字段排序

时间:2017-04-10 06:19:29

标签: go

我有以下结构:

type Parent struct {
    id       string
    children []Child
}

type Child struct {
    id string
}

我已经制作了一些具有以下值的父母:

parents := make([]Parent, 0)

p1 := Parent {
    "3",
    []Child {
        {"2"},
        {"3"},
        {"1"},
    },
}

p2 := Parent {
    "1",
    []Child {
        {"8"},
        {"9"},
        {"7"},
    },
}

p3 := Parent {
    "2",
    []Child {
        {"5"},
        {"6"},
        {"4"},
    },
}             

parents = append(parents, p1, p2, p3)

我正在尝试按以下顺序对“父母”切片进行排序:

1) First, sort all Parents by Parent.id

2) Next, sort each Parent's "children" slice by Child.id

预期结果如下:

[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]

有没有办法在Go中执行此操作?

1 个答案:

答案 0 :(得分:3)

我使用以下代码让它工作:

// 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})
}

特别感谢@Volker提及 sort.Slice 功能!我不知道它存在!