英文:
Go sort slice of pointers
问题
考虑以下代码的翻译:
type Item struct {
Title string
Date time.Time
}
type Items []Item
func (slice Items) Len() int {
return len(slice)
}
func (slice Items) Less(i, j int) bool {
return slice[i].Date.After(slice[j].Date)
}
func (slice Items) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
在主方法中,我有一个指向Item
的指针切片,需要对其进行排序。我的尝试是:
items := make(Items, len(in.Items)) // in.Items 的类型为 []*Item
for i, value := range in.Items {
items[i] = *value
}
sort.Sort(items)
in.Items = make([]*Item, len(items))
for i, value := range items {
in.Items[i] = &value
}
虽然这样做可以达到我想要的效果,但还有其他方法可以实现吗?
英文:
Consider the following:
type Item struct {
Title string
Date time.Time
}
type Items []Item
func (slice Items) Len() int {
return len(slice)
}
func (slice Items) Less(i, j int) bool {
return slice[i].Date.After(slice[j].Date)
}
func (slice Items) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
In the main method, I have a slice of pointers to Item
, that must be sorted. My attempt is:
items := make(Items, len(in.Items)) //in.Items is of type []*Item
for i, value := range in.Items {
items[i] = *value
}
sort.Sort(items)
in.Items = make([]*Item, len(items))
for i, value := range items {
in.Items[i] = &value
}
While it does what I need, is there another way to do this?
答案1
得分: 8
只需将Items
定义为一个项目指针的列表:
type Items []*Item
然后,您可以使用您已经描述的方法对其进行排序。就是这样。
英文:
Just make Items
a list of item pointers:
type Items []*Item
and it can be sorted with the methods you've already described. that's it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论