(任意)字段名称对结构数组进行简单排序的最简单方法是什么? [英] What is the shortest way to simply sort an array of structs by (arbitrary) field names?

查看:129
本文介绍了(任意)字段名称对结构数组进行简单排序的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,我有一堆结构,例如

I just had a problem where I had an array of structs, e.g.

package main

import "log"

type Planet struct {
    Name       string  `json:"name"`
    Aphelion   float64 `json:"aphelion"`   // in million km
    Perihelion float64 `json:"perihelion"` // in million km
    Axis       int64   `json:"Axis"`       // in km
    Radius     float64 `json:"radius"`
}

func main() {
    var mars = new(Planet)
    mars.Name = "Mars"
    mars.Aphelion = 249.2
    mars.Perihelion = 206.7
    mars.Axis = 227939100
    mars.Radius = 3389.5

    var earth = new(Planet)
    earth.Name = "Earth"
    earth.Aphelion = 151.930
    earth.Perihelion = 147.095
    earth.Axis = 149598261
    earth.Radius = 6371.0

    var venus = new(Planet)
    venus.Name = "Venus"
    venus.Aphelion = 108.939
    venus.Perihelion = 107.477
    venus.Axis = 108208000
    venus.Radius = 6051.8

    planets := [...]Planet{*mars, *venus, *earth}
    log.Println(planets)
}

假设您想按 Axis 。你怎么做?

Lets say you want to sort it by Axis. How do you do that?

(注意:我看过 http://golang.org/pkg/sort/ ,它似乎工作,但我必须添加约20行,只是为了简单的排序通过一个非常简单的键。我有一个python背景,它是简单的 sorted(planets,key = lambda n:n.Axis) - Go有没有类似的简单方法?)

(Note: I have seen http://golang.org/pkg/sort/ and it seems to work, but I have to add about 20 lines just for simple sorting by a very simple key. I have a python background where it is as simple as sorted(planets, key=lambda n: n.Axis) - is there something similar simple in Go?)

推荐答案

如果你想要比标准库 sort 包少一些细节,你可以使用第三方 github.com/bradfitz/slice 包。它使用一些技巧来生成排序切片所需的 Len Swap 方法,因此您只需要提供少于方法。

If you want something a bit less verbose than the standard library sort package, you could use the third party github.com/bradfitz/slice package. It uses some tricks to generate the Len and Swap methods needed to sort your slice, so you only need to provide a Less method.

使用此包,您可以执行以下操作:

With this package, you can perform the sort with:

slice.Sort(planets[:], func(i, j int) bool {
    return planets[i].Axis < planets[j].Axis
})

planets [:] 部分对于生成覆盖阵列的切片是必需的。如果您制作行星切片而不是数组,您可以跳过该部分。

The planets[:] part is necessary to produce a slice covering your array. If you make planets a slice instead of an array you could skip that part.

这篇关于(任意)字段名称对结构数组进行简单排序的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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