0%

go实现generator

这是一篇短文。

用过python的都知道generator,也就是生成器。生成器函数返回一个迭代器。那么如果用golang如何来实现呢?两种方法:channel和闭包。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main

import (
"fmt"
)

//implement generator by closure
func FibnacciClosure() func() (ret int) {
a, b := 0, 1
return func() (ret int) {
ret = b
a, b = b, a+b
return
}
}

//implement generator by channel
func FibnacciChan(n int) chan int {
ret := make(chan int)

go func() {
a, b := 0, 1
for i := 0; i < n; i++ {
ret <- b
a, b = b, a+b
}
close(ret)
}()

return ret
}

func main() {
//closure
nextFib := FibnacciClosure()
for i := 0; i < 20; i++ {
fmt.Println(nextFib())
}

//channel
for i := range FibnacciChan(20) {
fmt.Println(i)
}
}