github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/go4gophers/organs2.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"sort"
     8  )
     9  
    10  type Organ struct {
    11  	Name   string
    12  	Weight Grams
    13  }
    14  
    15  func (o *Organ) String() string { return fmt.Sprintf("%v (%v)", o.Name, o.Weight) }
    16  
    17  type Grams int
    18  
    19  func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
    20  
    21  // PART1 OMIT
    22  
    23  type Organs []*Organ
    24  
    25  func (s Organs) Len() int      { return len(s) }
    26  func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
    27  
    28  // PART2 OMIT
    29  
    30  type ByName struct{ Organs }
    31  
    32  func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
    33  
    34  type ByWeight struct{ Organs }
    35  
    36  func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
    37  
    38  // PART3 OMIT
    39  
    40  func main() {
    41  	// START OMIT
    42  	s := []*Organ{
    43  		{"brain", 1340},
    44  		{"heart", 290},
    45  		{"liver", 1494},
    46  		{"pancreas", 131},
    47  		{"spleen", 162},
    48  	}
    49  
    50  	sort.Sort(ByWeight{s}) // HL
    51  	printOrgans("Organs by weight", s)
    52  
    53  	sort.Sort(ByName{s}) // HL
    54  	printOrgans("Organs by name", s)
    55  	// STOP OMIT
    56  }
    57  
    58  func printOrgans(t string, s []*Organ) {
    59  	fmt.Printf("%s:\n", t)
    60  	for _, o := range s {
    61  		fmt.Printf("  %v\n", o)
    62  	}
    63  }