Go: How to sort a custom type in Go

  • Use the function sort.Slice. It sorts a slice using a provided less(i, j int) bool function.
  • To sort the slice while keeping the original order of equal elements, use sort.SliceStable instead.
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!