英文:
Sorting by slice fields
问题
我有以下的结构体:
type Parent struct {
id string
children []Child
}
type Child struct {
id string
}
我创建了一个包含以下数值的 Parents
切片:
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)
我想按照以下顺序对 parents
切片进行排序:
-
首先,按照
Parent.id
对所有的Parents
进行排序。 -
接下来,按照每个
Parent
的children
切片中的Child.id
进行排序。
期望的结果类似于:
[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]
在 Go 中有没有一种方法可以实现这个排序?
英文:
I have the following Structs:
type Parent struct {
id string
children []Child
}
type Child struct {
id string
}
I have made a slice of Parents with the following values:
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)
I am trying to sort the "parents" slice in the following order:
1) First, sort all Parents by Parent.id
2) Next, sort each Parent's "children" slice by Child.id
The expected result is something like:
[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]
Is there a way to do this in Go?
答案1
得分: 5
我用以下代码使其工作:
// 按照 Id 对 parents 切片中的每个 Parent 进行排序
sort.Slice(parents, func(i, j int) bool {return parents[i].id < parents[j].id})
// 对于每个 Parent,按照 Id 对 children 切片中的每个 Child 进行排序
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 函数!我之前不知道它的存在!
英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论