Generator Pattern
Generators yields a sequence of values one at a time.
发生器每次产生一个值序列。
Implementation1
2
3
4
5
6
7
8
9
10
11
12
13
14func Count(start int, end int) chan int {
ch := make(chan int)
go func(ch chan int) {
for i := start; i <= end ; i++ {
// Blocks on the operation
ch <- i
}
close(ch)
}(ch)
return ch
}
Usage1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16fmt.Println("No bottles of beer on the wall")
for i := range Count(1, 99) {
fmt.Println("Pass it around, put one up,", i, "bottles of beer on the wall")
// Pass it around, put one up, 1 bottles of beer on the wall
// Pass it around, put one up, 2 bottles of beer on the wall
// ...
// Pass it around, put one up, 99 bottles of beer on the wall
//把它们放在一边,把一瓶啤酒放在墙上
//将它们穿过,放一个,墙上2瓶啤酒
// ......
//把它倒过来,把1瓶啤酒放在墙上
// 哈哈哈,神机翻
}
fmt.Println(100, "bottles of beer on the wall")