example_interface_test.go 896 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. sort.Sort(ByAge(people))
  31. fmt.Println(people)
  32. // Output:
  33. // [Bob: 31 John: 42 Michael: 17 Jenny: 26]
  34. // [Michael: 17 Jenny: 26 Bob: 31 John: 42]
  35. }