File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -6,6 +6,7 @@ title: 碎碎念
6
6
7
7
“碎碎念”是本站发布日常随笔的栏目,内容包括项目进展、小点子、有趣的讨论等。
8
8
9
+ - 2025-03-24: [ 凹语言支持for range迭代器] ( st0074.md )
9
10
- 2025-03-04: [ 凹语言被维基百科收录] ( st0073.md )
10
11
- 2025-02-28: [ 武汉晚报:20多位开发者“凹”出编程“凹语言”] ( st0072.md )
11
12
- 2025-02-27: [ 凹语言登上长江日报] ( st0071.md )
Original file line number Diff line number Diff line change
1
+ # 凹语言支持for range迭代器
2
+
3
+ - 时间:2025-03-24
4
+ - 撰稿:凹语言 开发组
5
+ - 转载请注明原文链接:[ https://wa-lang.org/smalltalk/st0074.html ] ( https://wa-lang.org/smalltalk/st0074.html )
6
+
7
+ ---
8
+
9
+ 在新发布的 [ v0.22.0] ( https://gitcode.com/wa-lang/wa/releases/v0.22.0 ) 版本中实验性地引入了for range迭代器支持。比如内置了对整数值迭代的支持:
10
+
11
+ ``` wa
12
+ func main {
13
+ for i := range 3 {
14
+ println(i)
15
+ }
16
+ }
17
+ ```
18
+
19
+ 本质上这和运算符重载是类似的特性,这里是` range ` 运算符内置对整数进行的重载。更有趣的是` range ` 运算符还针对可被调用对象进行了重载,这样就可以实现自定义迭代器的能力:
20
+
21
+ ``` wa
22
+ type MyObject :struct {
23
+ elems: []string
24
+ }
25
+
26
+ func New(a: ...string) => *MyObject {
27
+ return &MyObject{elems: a}
28
+ }
29
+
30
+ func MyObject.Iter => func => (ok: bool, k: int, v: string) {
31
+ idx: int
32
+ return func => (ok: bool, k: int, v: string) {
33
+ if ok = idx < len(this.elems); ok {
34
+ k, v = idx, this.elems[idx]
35
+ idx++
36
+ }
37
+ return
38
+ }
39
+ }
40
+
41
+ func main {
42
+ for i, v := range New("aa", "bb", "cc").Iter() {
43
+ println(i, v)
44
+ }
45
+ }
46
+ ```
47
+
48
+ 其中MyObject类型的Iter方法返回的是一个闭包函数对象:该闭包函数返回ok、key和value三个值,其中ok决定何时迭代终止,后续的2个返回值可以根据需要省略一个。
49
+
50
+ 运行的结果如下:
51
+
52
+ ```
53
+ $ wa run a.out.wa
54
+ 0 aa
55
+ 1 bb
56
+ 2 cc
57
+ ```
58
+
59
+ 目前这是一个实验性的特性,未来开发组将根据真实开发场景做调整和完善,也欢迎社区同学参与讨论。
You can’t perform that action at this time.
0 commit comments