From: jiahua wang Date: Wed, 7 Aug 2024 06:43:14 +0000 (+0800) Subject: slices: add examples for iterator-related functions X-Git-Tag: go1.24rc1~1205 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=3c170ac018422fce5811f23455c89fe7630a4156;p=gostls13.git slices: add examples for iterator-related functions Change-Id: I13e878579b51638c2c07ad3ea99be7276177875c Reviewed-on: https://go-review.googlesource.com/c/go/+/603735 Reviewed-by: Ian Lance Taylor Reviewed-by: Carlos Amedee Auto-Submit: Ian Lance Taylor LUCI-TryBot-Result: Go LUCI --- diff --git a/src/slices/example_test.go b/src/slices/example_test.go index cb601ada0a..fb93f6e79f 100644 --- a/src/slices/example_test.go +++ b/src/slices/example_test.go @@ -385,6 +385,133 @@ func ExampleRepeat() { // [0 1 2 3 0 1 2 3] } +func ExampleAll() { + names := []string{"Alice", "Bob", "Vera"} + for i, v := range slices.All(names) { + fmt.Println(i, ":", v) + } + // Output: + // 0 : Alice + // 1 : Bob + // 2 : Vera +} + +func ExampleBackward() { + names := []string{"Alice", "Bob", "Vera"} + for i, v := range slices.Backward(names) { + fmt.Println(i, ":", v) + } + // Output: + // 2 : Vera + // 1 : Bob + // 0 : Alice +} + +func ExampleValues() { + names := []string{"Alice", "Bob", "Vera"} + for v := range slices.Values(names) { + fmt.Println(v) + } + // Output: + // Alice + // Bob + // Vera +} + +func ExampleAppendSeq() { + seq := func(yield func(int) bool) { + for i := 0; i < 10; i += 2 { + if !yield(i) { + return + } + } + } + + s := slices.AppendSeq([]int{1, 2}, seq) + fmt.Println(s) + // Output: + // [1 2 0 2 4 6 8] +} + +func ExampleCollect() { + seq := func(yield func(int) bool) { + for i := 0; i < 10; i += 2 { + if !yield(i) { + return + } + } + } + + s := slices.Collect(seq) + fmt.Println(s) + // Output: + // [0 2 4 6 8] +} + +func ExampleSorted() { + seq := func(yield func(int) bool) { + flag := -1 + for i := 0; i < 10; i += 2 { + flag = -flag + if !yield(i * flag) { + return + } + } + } + + s := slices.Sorted(seq) + fmt.Println(s) + fmt.Println(slices.IsSorted(s)) + // Output: + // [-6 -2 0 4 8] + // true +} + +func ExampleSortedFunc() { + seq := func(yield func(int) bool) { + flag := -1 + for i := 0; i < 10; i += 2 { + flag = -flag + if !yield(i * flag) { + return + } + } + } + + sortFunc := func(a, b int) int { + return cmp.Compare(b, a) // the comparison is being done in reverse + } + + s := slices.SortedFunc(seq, sortFunc) + fmt.Println(s) + // Output: + // [8 4 0 -2 -6] +} + +func ExampleSortedStableFunc() { + type Person struct { + Name string + Age int + } + + people := []Person{ + {"Gopher", 13}, + {"Alice", 20}, + {"Bob", 5}, + {"Vera", 24}, + {"Zac", 20}, + } + + sortFunc := func(x, y Person) int { + return cmp.Compare(x.Age, y.Age) + } + + s := slices.SortedStableFunc(slices.Values(people), sortFunc) + fmt.Println(s) + // Output: + // [{Bob 5} {Gopher 13} {Alice 20} {Zac 20} {Vera 24}] +} + func ExampleChunk() { type Person struct { Name string