github.com/camlistore/go4@v0.0.0-20200104003542-c7e774b10ea0/sort/example_interface_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  
    10  	"go4.org/sort"
    11  )
    12  
    13  type Person struct {
    14  	Name string
    15  	Age  int
    16  }
    17  
    18  func (p Person) String() string {
    19  	return fmt.Sprintf("%s: %d", p.Name, p.Age)
    20  }
    21  
    22  // ByAge implements sort.Interface for []Person based on
    23  // the Age field.
    24  type ByAge []Person
    25  
    26  func (a ByAge) Len() int           { return len(a) }
    27  func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
    28  func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
    29  
    30  func ExampleSort() {
    31  	people := []Person{
    32  		{"Bob", 31},
    33  		{"John", 42},
    34  		{"Michael", 17},
    35  		{"Jenny", 26},
    36  	}
    37  
    38  	fmt.Println(people)
    39  	sort.Sort(ByAge(people))
    40  	fmt.Println(people)
    41  
    42  	// Output:
    43  	// [Bob: 31 John: 42 Michael: 17 Jenny: 26]
    44  	// [Michael: 17 Jenny: 26 Bob: 31 John: 42]
    45  }