Skip to content

Instantly share code, notes, and snippets.

@DavidVaini
Created October 15, 2013 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidVaini/6993410 to your computer and use it in GitHub Desktop.
Save DavidVaini/6993410 to your computer and use it in GitHub Desktop.
Sorting a list of structs/objects based on the object's properties.
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Weight int
Iq int
}
type People []*Person
func (p People) Len() int { return len(p) }
func (p People) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
type ByName struct{ People }
func (p ByName) Less(i, j int) bool { return p.People[i].Name < p.People[j].Name }
type ByWeight struct{ People }
func (p ByWeight) Less(i, j int) bool { return p.People[i].Weight < p.People[j].Weight }
type ByIq struct {People}
func (p ByIq) Less(i, j int) bool { return p.People[i].Iq < p.People[j].Iq }
func main() {
p := []*Person{
{"Bob", 135, 104},
{"Gary", 165, 108},
{"Frank", 183,100},
{"Troy", 320,108},
{"Sam", 144,150},
{"Sean", 144,88},
}
sort.Sort(ByIq{p})
fmt.Println("People by Iq:")
for _, person := range p {
fmt.Printf("%-8s (Weight: %v) (IQ: %v) \n", person.Name, person.Weight, person.Iq)
}
sort.Sort(ByWeight{p})
fmt.Println("People by weight:")
for _, person := range p {
fmt.Printf("%-8s (Weight: %v) (IQ: %v) \n", person.Name, person.Weight, person.Iq)
}
sort.Sort(ByName{p})
fmt.Println("People by name:")
for _, person := range p {
fmt.Printf("%-8s (Weight: %v) (IQ: %v) \n", person.Name, person.Weight, person.Iq)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment