Sorting Slices
Sort a Slice
package golang
import "sort"
type Person struct {
Name string
Age int
}
func New(name string, age int) *Person {
return &Person{
Name: name,
Age: age,
}
}
func SortPeople(people []*Person) {
sort.Slice(people, func(i, j int) bool {
if people[i].Name == people[i].Name {
// This is descending order by age.
return people[i].Age > people[j].Age
}
// ascending order by name
return people[i].Name < people[j].Name
})
}
func Run() {
people := []*Person{
New("bob", 30),
New("jane", 24),
New("bob", 17),
New("jane", 46),
}
SortPeople(people)
}
import "sort"
type Person struct {
Name string
Age int
}
func New(name string, age int) *Person {
return &Person{
Name: name,
Age: age,
}
}
func SortPeople(people []*Person) {
sort.Slice(people, func(i, j int) bool {
if people[i].Name == people[i].Name {
// This is descending order by age.
return people[i].Age > people[j].Age
}
// ascending order by name
return people[i].Name < people[j].Name
})
}
func Run() {
people := []*Person{
New("bob", 30),
New("jane", 24),
New("bob", 17),
New("jane", 46),
}
SortPeople(people)
}