|
| 1 | +// All material is licensed under the Apache License Version 2.0, January 2004 |
| 2 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 3 | + |
| 4 | +// Sample program shows how to use the Compare API from the slices package. |
| 5 | +package main |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + |
| 10 | + "golang.org/x/exp/slices" |
| 11 | +) |
| 12 | + |
| 13 | +// result translates the result of the compare API. |
| 14 | +var result = map[int]string{ |
| 15 | + -1: "First slice is shorter", |
| 16 | + 0: "Both slices are equal", |
| 17 | + 1: "Second slice is shorter", |
| 18 | +} |
| 19 | + |
| 20 | +// Compare compares the elements between two slices. The elements are compared |
| 21 | +// sequentially, starting at index 0, until one element is not equal to the |
| 22 | +// other. The result of comparing the first non-matching elements is returned. |
| 23 | + |
| 24 | +func main() { |
| 25 | + list1 := []int{1, 2, 3, 4, 5} |
| 26 | + list2 := []int{1, 2, 6, 4, 5, 6} |
| 27 | + list3 := []int{1, 2, 3, 4} |
| 28 | + list4 := []int{1, 2, 3, 4} |
| 29 | + |
| 30 | + fmt.Println("Slice1", list1) |
| 31 | + fmt.Println("Slice2", list2) |
| 32 | + fmt.Println("Slice3", list3) |
| 33 | + fmt.Println("Slice4", list4) |
| 34 | + |
| 35 | + // ------------------------------------------------------------------------- |
| 36 | + // Compare list1 and list2 |
| 37 | + |
| 38 | + fmt.Printf("list1 vs list2: Compare(%s), Func(%s)\n", |
| 39 | + result[slices.Compare(list1, list2)], |
| 40 | + result[slices.CompareFunc(list1, list2, compare)], |
| 41 | + ) |
| 42 | + |
| 43 | + // ------------------------------------------------------------------------- |
| 44 | + // Compare list1 and list3 |
| 45 | + |
| 46 | + fmt.Printf("list1 vs list3: Compare(%s), Func(%s)\n", |
| 47 | + result[slices.Compare(list1, list3)], |
| 48 | + result[slices.CompareFunc(list1, list3, compare)], |
| 49 | + ) |
| 50 | + |
| 51 | + // ------------------------------------------------------------------------- |
| 52 | + // Compare list3 and list4 |
| 53 | + |
| 54 | + fmt.Printf("list3 vs list4: Compare(%s), Func(%s)\n", |
| 55 | + result[slices.Compare(list3, list4)], |
| 56 | + result[slices.CompareFunc(list3, list4, compare)], |
| 57 | + ) |
| 58 | +} |
| 59 | + |
| 60 | +// compare evaluates values in increasing index order, and the comparisons stop |
| 61 | +// after the first time the function returns non-zero. Return 0 is the two |
| 62 | +// values match, return -1 if a < b, and 1 if a > b. |
| 63 | +func compare(a int, b int) int { |
| 64 | + if a < b { |
| 65 | + return -1 |
| 66 | + } |
| 67 | + |
| 68 | + if a > b { |
| 69 | + return 1 |
| 70 | + } |
| 71 | + |
| 72 | + return 0 |
| 73 | +} |
0 commit comments