dongqiyou0303 2017-04-10 06:19
浏览 749
已采纳

Golang:按切片字段排序

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条回答 默认 最新

  • dsqtl335227 2017-04-10 07:05
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低