Go: How to sort a custom type in Go

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

// Sort by age, keeping original order or equal elements.
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}]

Comments

Be the first to comment!