| 1 |
package a |
| 2 |
|
| 3 |
import "sort" |
| 4 |
|
| 5 |
|
| 6 |
func IncorrectSort() { |
| 7 |
i := 5 |
| 8 |
sortFn := func(i, j int) bool { return false } |
| 9 |
sort.Slice(i, sortFn) |
| 10 |
sort.SliceStable(i, sortFn) |
| 11 |
sort.SliceIsSorted(i, sortFn) |
| 12 |
} |
| 13 |
|
| 14 |
|
| 15 |
func CorrectSort() { |
| 16 |
s := []int{2, 3, 5, 6} |
| 17 |
sortFn := func(i, j int) bool { return s[i] < s[j] } |
| 18 |
sort.Slice(s, sortFn) |
| 19 |
sort.SliceStable(s, sortFn) |
| 20 |
sort.SliceIsSorted(s, sortFn) |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
func CorrectInterface() { |
| 26 |
var s interface{} |
| 27 |
s = interface{}([]int{2, 1, 0}) |
| 28 |
sortFn := func(i, j int) bool { return s.([]int)[i] < s.([]int)[j] } |
| 29 |
sort.Slice(s, sortFn) |
| 30 |
sort.SliceStable(s, sortFn) |
| 31 |
sort.SliceIsSorted(s, sortFn) |
| 32 |
} |
| 33 |
|
| 34 |
type slicecompare interface { |
| 35 |
compare(i, j int) bool |
| 36 |
} |
| 37 |
|
| 38 |
type intslice []int |
| 39 |
|
| 40 |
func (s intslice) compare(i, j int) bool { |
| 41 |
return s[i] < s[j] |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
func UnderlyingInterface() { |
| 47 |
var s slicecompare |
| 48 |
s = intslice([]int{2, 1, 0}) |
| 49 |
sort.Slice(s, s.compare) |
| 50 |
sort.SliceStable(s, s.compare) |
| 51 |
sort.SliceIsSorted(s, s.compare) |
| 52 |
} |
| 53 |
|
| 54 |
type mySlice []int |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
func UnderlyingSlice() { |
| 59 |
s := mySlice{2, 3, 5, 6} |
| 60 |
sortFn := func(i, j int) bool { return s[i] < s[j] } |
| 61 |
sort.Slice(s, sortFn) |
| 62 |
sort.SliceStable(s, sortFn) |
| 63 |
sort.SliceIsSorted(s, sortFn) |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
func FunctionResultsAsArguments() { |
| 69 |
s := []string{"a", "z", "ooo"} |
| 70 |
sort.Slice(less(s)) |
| 71 |
sort.Slice(lessPtr(s)) |
| 72 |
} |
| 73 |
|
| 74 |
func less(s []string) ([]string, func(i, j int) bool) { |
| 75 |
return s, func(i, j int) bool { |
| 76 |
return s[i] < s[j] |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
func lessPtr(s []string) (*[]string, func(i, j int) bool) { |
| 81 |
return &s, func(i, j int) bool { |
| 82 |
return s[i] < s[j] |
| 83 |
} |
| 84 |
} |