github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/sort/example_wrapper_test.go (about)

     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  
     5  package sort_test
     6  
     7  import (
     8  	"fmt"
     9  	"sort"
    10  )
    11  
    12  type Grams int
    13  
    14  func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
    15  
    16  type Organ struct {
    17  	Name   string
    18  	Weight Grams
    19  }
    20  
    21  type Organs []*Organ
    22  
    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] }
    25  
    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 }
    29  
    30  func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
    31  
    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 }
    35  
    36  func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
    37  
    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},
    46  	}
    47  
    48  	sort.Sort(ByWeight{s})
    49  	fmt.Println("Organs by weight:")
    50  	printOrgans(s)
    51  
    52  	sort.Sort(ByName{s})
    53  	fmt.Println("Organs by name:")
    54  	printOrgans(s)
    55  
    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)
    71  }
    72  
    73  func printOrgans(s []*Organ) {
    74  	for _, o := range s {
    75  		fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
    76  	}
    77  }