example_wrapper_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 Grams int
  10. func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
  11. type Organ struct {
  12. Name string
  13. Weight Grams
  14. }
  15. type Organs []*Organ
  16. func (s Organs) Len() int { return len(s) }
  17. func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  18. // ByName implements sort.Interface by providing Less and using the Len and
  19. // Swap methods of the embedded Organs value.
  20. type ByName struct{ Organs }
  21. func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
  22. // ByWeight implements sort.Interface by providing Less and using the Len and
  23. // Swap methods of the embedded Organs value.
  24. type ByWeight struct{ Organs }
  25. func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
  26. func Example_sortWrapper() {
  27. s := []*Organ{
  28. {"brain", 1340},
  29. {"heart", 290},
  30. {"liver", 1494},
  31. {"pancreas", 131},
  32. {"prostate", 62},
  33. {"spleen", 162},
  34. }
  35. sort.Sort(ByWeight{s})
  36. fmt.Println("Organs by weight:")
  37. printOrgans(s)
  38. sort.Sort(ByName{s})
  39. fmt.Println("Organs by name:")
  40. printOrgans(s)
  41. // Output:
  42. // Organs by weight:
  43. // prostate (62g)
  44. // pancreas (131g)
  45. // spleen (162g)
  46. // heart (290g)
  47. // brain (1340g)
  48. // liver (1494g)
  49. // Organs by name:
  50. // brain (1340g)
  51. // heart (290g)
  52. // liver (1494g)
  53. // pancreas (131g)
  54. // prostate (62g)
  55. // spleen (162g)
  56. }
  57. func printOrgans(s []*Organ) {
  58. for _, o := range s {
  59. fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
  60. }
  61. }