diff --git a/xx-sortby.go b/xx-sortby.go new file mode 100644 index 0000000..712a71a --- /dev/null +++ b/xx-sortby.go @@ -0,0 +1,48 @@ +package main + +import ("fmt" ; "sort") + +type Person struct { + Name string + Age int +} + +type ByName []Person +func (this ByName) Len() int { + return len(this) +} +func (this ByName) Less(i, j int) bool { + return this[i].Name < this[j].Name +} +func (this ByName) Swap(i, j int) { + this[i], this[j] = this[j], this[i] +} + +type ByAge []Person +func (this ByAge) Len() int { + return len(this) +} +func (this ByAge) Less(i, j int) bool { + return this[i].Age < this[j].Age +} +func (this ByAge) Swap(i, j int) { + this[i], this[j] = this[j], this[i] +} + +func main() { + kids := []Person{ + {"Jack", 10}, + {"Jill", 9}, + {"Bob", 12}, + } + fmt.Println("Original:", kids) + fmt.Println() + + sort.Sort(ByName(kids)) + fmt.Println("ByName: ", kids) + fmt.Println() + + sort.Sort(ByAge(kids)) + fmt.Println("ByAge: ", kids) + fmt.Println() +}