Skip to content

Commit 41357fb

Browse files
authored
Merge pull request #876 from devlights/add-go123-iter-examples
2 parents e2e8993 + 62f809a commit 41357fb

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

examples/basic/iters/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ func NewRegister() mapping.Register {
1717
func (r *register) Regist(m mapping.ExampleMapping) {
1818
m["iters_range_over_func_1"] = Go123RangeOverFunc1
1919
m["iters_range_over_func_2"] = Go123RangeOverFunc2
20+
m["iters_range_over_func_3"] = Go123RangeOverFunc3
2021
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package iters
2+
3+
import (
4+
"strconv"
5+
6+
"github.com/devlights/gomy/output"
7+
)
8+
9+
// Go123RangeOverFunc3 は、Go 1.23 で正式導入となった Range-Over-Func のサンプルです。
10+
//
11+
// Range-Over-Func は、独自のイテレータを作成出来るようになる機能です。
12+
// 以下の関数パターンがサポートされています。
13+
//
14+
// - func(func() bool) : ループ変数に値を渡さないタイプ
15+
// - func(func(v) bool) : 1つのループ変数に値を渡すタイプ
16+
// - func(func(k, v) bool) : 2つのループ変数に値を渡すタイプ
17+
//
18+
// 本サンプルは、func(func(k, v) bool) (2つのループ変数に値を渡すタイプ) についてのサンプルです。
19+
//
20+
// # REFERENCES
21+
// - https://tip.golang.org/doc/go1.23
22+
// - https://tip.golang.org/blog/range-functions
23+
// - https://tip.golang.org/ref/spec#For_range
24+
// - https://pkg.go.dev/iter@go1.23.3
25+
// - https://zenn.dev/koya_iwamura/articles/7e7482c7222e37
26+
// - https://tech.every.tv/entry/2023/12/09/1
27+
// - https://future-architect.github.io/articles/20240129a/
28+
func Go123RangeOverFunc3() error {
29+
var (
30+
// 2回分のイテレータ。2つのループ変数に値を渡すタイプ。
31+
twoTimes = func(yield func(i int, s string) bool) {
32+
if !yield(0, strconv.Itoa(100)) {
33+
return
34+
}
35+
36+
if !yield(1, strconv.Itoa(99)) {
37+
return
38+
}
39+
}
40+
// 指定された文字列を逆順でループ
41+
reverse = func(s string) func(func(int, string) bool) {
42+
var (
43+
runes = []rune(s)
44+
runeLen = len(runes)
45+
)
46+
47+
return func(yield func(i int, s string) bool) {
48+
for i, j := 0, runeLen-1; i < runeLen; i, j = i+1, j-1 {
49+
if !yield(i, string(runes[j])) {
50+
return
51+
}
52+
}
53+
}
54+
}
55+
)
56+
57+
// func(func(k, v) bool) のイテレータなので、ループ毎に2つのループ変数を受け取る。
58+
for i, v := range twoTimes {
59+
output.Stdoutf("[twoTimes ]", "%d:%v\n", i, v)
60+
}
61+
62+
for i, v := range reverse("helloworld") {
63+
output.Stdoutf("[reverse(helloworld)]", "%d:%v\n", i, v)
64+
}
65+
66+
return nil
67+
}

0 commit comments

Comments
 (0)