| 1 |
// Copyright 2021 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 foo_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"flag" |
| 9 |
"fmt" |
| 10 |
"log" |
| 11 |
"os/exec" |
| 12 |
"sort" |
| 13 |
) |
| 14 |
|
| 15 |
func ExampleHello() { |
| 16 |
fmt.Println("Hello, world!") |
| 17 |
// Output: Hello, world! |
| 18 |
} |
| 19 |
|
| 20 |
func ExampleImport() { |
| 21 |
out, err := exec.Command("date").Output() |
| 22 |
if err != nil { |
| 23 |
log.Fatal(err) |
| 24 |
} |
| 25 |
fmt.Printf("The date is %s\n", out) |
| 26 |
} |
| 27 |
|
| 28 |
func ExampleKeyValue() { |
| 29 |
v := struct { |
| 30 |
a string |
| 31 |
b int |
| 32 |
}{ |
| 33 |
a: "A", |
| 34 |
b: 1, |
| 35 |
} |
| 36 |
fmt.Print(v) |
| 37 |
// Output: a: "A", b: 1 |
| 38 |
} |
| 39 |
|
| 40 |
func ExampleKeyValueImport() { |
| 41 |
f := flag.Flag{ |
| 42 |
Name: "play", |
| 43 |
} |
| 44 |
fmt.Print(f) |
| 45 |
// Output: Name: "play" |
| 46 |
} |
| 47 |
|
| 48 |
var keyValueTopDecl = struct { |
| 49 |
a string |
| 50 |
b int |
| 51 |
}{ |
| 52 |
a: "B", |
| 53 |
b: 2, |
| 54 |
} |
| 55 |
|
| 56 |
func ExampleKeyValueTopDecl() { |
| 57 |
fmt.Print(keyValueTopDecl) |
| 58 |
// Output: a: "B", b: 2 |
| 59 |
} |
| 60 |
|
| 61 |
// Person represents a person by name and age. |
| 62 |
type Person struct { |
| 63 |
Name string |
| 64 |
Age int |
| 65 |
} |
| 66 |
|
| 67 |
// String returns a string representation of the Person. |
| 68 |
func (p Person) String() string { |
| 69 |
return fmt.Sprintf("%s: %d", p.Name, p.Age) |
| 70 |
} |
| 71 |
|
| 72 |
// ByAge implements sort.Interface for []Person based on |
| 73 |
// the Age field. |
| 74 |
type ByAge []Person |
| 75 |
|
| 76 |
// Len returns the number of elements in ByAge. |
| 77 |
func (a ByAge) Len() int { return len(a) } |
| 78 |
|
| 79 |
// Swap swaps the elements in ByAge. |
| 80 |
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 81 |
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age } |
| 82 |
|
| 83 |
// people is the array of Person |
| 84 |
var people = []Person{ |
| 85 |
{"Bob", 31}, |
| 86 |
{"John", 42}, |
| 87 |
{"Michael", 17}, |
| 88 |
{"Jenny", 26}, |
| 89 |
} |
| 90 |
|
| 91 |
func ExampleSort() { |
| 92 |
fmt.Println(people) |
| 93 |
sort.Sort(ByAge(people)) |
| 94 |
fmt.Println(people) |
| 95 |
// Output: |
| 96 |
// [Bob: 31 John: 42 Michael: 17 Jenny: 26] |
| 97 |
// [Michael: 17 Jenny: 26 Bob: 31 John: 42] |
| 98 |
} |