example_interface_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package sort_test
  5. import (
  6. "fmt"
  7. "sort"
  8. )
  9. type Person struct {
  10. Name string
  11. Age int
  12. }
  13. func (p Person) String() string {
  14. return fmt.Sprintf("%s: %d", p.Name, p.Age)
  15. }
  16. // ByAge implements sort.Interface for []Person based on
  17. // the Age field.
  18. type ByAge []Person
  19. func (a ByAge) Len() int { return len(a) }
  20. func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  21. func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
  22. func Example() {
  23. people := []Person{
  24. {"Bob", 31},
  25. {"John", 42},
  26. {"Michael", 17},
  27. {"Jenny", 26},
  28. }
  29. fmt.Println(people)
  30. // There are two ways to sort a slice. First, one can define
  31. // a set of methods for the slice type, as with ByAge, and
  32. // call sort.Sort. In this first example we use that technique.
  33. sort.Sort(ByAge(people))
  34. fmt.Println(people)
  35. // The other way is to use sort.Slice with a custom Less
  36. // function, which can be provided as a closure. In this
  37. // case no methods are needed. (And if they exist, they
  38. // are ignored.) Here we re-sort in reverse order: compare
  39. // the closure with ByAge.Less.
  40. sort.Slice(people, func(i, j int) bool {
  41. return people[i].Age > people[j].Age
  42. })
  43. fmt.Println(people)
  44. // Output:
  45. // [Bob: 31 John: 42 Michael: 17 Jenny: 26]
  46. // [Michael: 17 Jenny: 26 Bob: 31 John: 42]
  47. // [John: 42 Bob: 31 Jenny: 26 Michael: 17]
  48. }