按切片字段排序 [英] Sorting by slice fields

查看:62
本文介绍了按切片字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

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

预期结果如下:

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

在Go中有办法做到这一点吗?

Is there a way to do this in Go?

推荐答案

我使用以下代码将其运行:

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

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

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

这篇关于按切片字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆