go4.org@v0.0.0-20230225012048-214862532bf5/sort/example_slice_test.go (about) 1 // Copyright 2016 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 func Example() { 14 people := []Person{ 15 {Name: "Bob", Age: 31}, 16 {Name: "John", Age: 42}, 17 {Name: "Michael", Age: 17}, 18 {Name: "Jenny", Age: 26}, 19 } 20 21 fmt.Println(people) 22 sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age }) 23 fmt.Println(people) 24 25 // Output: 26 // [Bob: 31 John: 42 Michael: 17 Jenny: 26] 27 // [Michael: 17 Jenny: 26 Bob: 31 John: 42] 28 } 29 30 func ExampleSlice() { 31 people := []Person{ 32 {Name: "Bob", Age: 31}, 33 {Name: "John", Age: 42}, 34 {Name: "Michael", Age: 17}, 35 {Name: "Jenny", Age: 26}, 36 } 37 38 fmt.Println(people) 39 sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age }) 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 }