Skip to content

Commit e2e8993

Browse files
authored
Merge pull request #875 from devlights/add-go123-iter-examples
2 parents 336381a + eaa6fa3 commit e2e8993

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

examples/basic/iters/examples.go

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

0 commit comments

Comments
 (0)