Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort slice of struct by specified field #12

Open
kevinyan815 opened this issue Oct 24, 2019 · 0 comments
Open

Sort slice of struct by specified field #12

kevinyan815 opened this issue Oct 24, 2019 · 0 comments

Comments

@kevinyan815
Copy link
Owner

kevinyan815 commented Oct 24, 2019

package main

import (
	"fmt"
	"strings"
	"sort"
)

func main() {
    family := []struct {
        Name string
        Age  int
    }{
        {"Alice", 23},
        {"David", 2},
        {"Eve", 2},
        {"Bob", 25},
    }

    // 用 age 排序,年龄相等的元素保持原始顺序
    sort.SliceStable(family, func(i, j int) bool {
        return family[i].Age < family[j].Age
    })
    fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]

    //下面实现排序order by age asc, name desc,如果 age 和 name 都相等则保持原始排序
    sort.SliceStable(family, func(i, j int) bool {
        if family[i].Age != family[j].Age {
            return family[i].Age < family[j].Age
        }
        return strings.Compare(family[i].Name, family[j].Name) == 1
    })

    fmt.Println(family) // [{Eve 2} {David 2} {Alice 23} {Bob 25}]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant