* tree-ssa-reassoc.c (reassociate_bb): Clarify code slighly.
[official-gcc.git] / libgo / go / sort / example_wrapper_test.go
blobcf6d74cf75469aa0fcc9df8fa2c8b1490ecc3188
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.
5 package sort_test
7 import (
8 "fmt"
9 "sort"
12 type Grams int
14 func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
16 type Organ struct {
17 Name string
18 Weight Grams
21 type Organs []*Organ
23 func (s Organs) Len() int { return len(s) }
24 func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
26 // ByName implements sort.Interface by providing Less and using the Len and
27 // Swap methods of the embedded Organs value.
28 type ByName struct{ Organs }
30 func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
32 // ByWeight implements sort.Interface by providing Less and using the Len and
33 // Swap methods of the embedded Organs value.
34 type ByWeight struct{ Organs }
36 func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
38 func Example_sortWrapper() {
39 s := []*Organ{
40 {"brain", 1340},
41 {"heart", 290},
42 {"liver", 1494},
43 {"pancreas", 131},
44 {"prostate", 62},
45 {"spleen", 162},
48 sort.Sort(ByWeight{s})
49 fmt.Println("Organs by weight:")
50 printOrgans(s)
52 sort.Sort(ByName{s})
53 fmt.Println("Organs by name:")
54 printOrgans(s)
56 // Output:
57 // Organs by weight:
58 // prostate (62g)
59 // pancreas (131g)
60 // spleen (162g)
61 // heart (290g)
62 // brain (1340g)
63 // liver (1494g)
64 // Organs by name:
65 // brain (1340g)
66 // heart (290g)
67 // liver (1494g)
68 // pancreas (131g)
69 // prostate (62g)
70 // spleen (162g)
73 func printOrgans(s []*Organ) {
74 for _, o := range s {
75 fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)