2016-09-06 10:45:18 +03:00
|
|
|
# Generator Pattern
|
|
|
|
|
2016-09-15 11:39:40 +03:00
|
|
|
[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time.
|
2016-09-06 10:45:18 +03:00
|
|
|
|
2016-09-15 11:39:40 +03:00
|
|
|
## Implementation
|
2016-09-07 09:48:35 +03:00
|
|
|
|
2016-09-15 11:39:40 +03:00
|
|
|
```go
|
|
|
|
func Count(start int, end int) chan int {
|
|
|
|
ch := make(chan int)
|
|
|
|
|
|
|
|
go func(ch chan int) {
|
2017-03-08 17:43:35 +03:00
|
|
|
for i := start; i <= end ; i++ {
|
2016-09-15 11:39:40 +03:00
|
|
|
// Blocks on the operation
|
2016-10-03 16:55:45 +03:00
|
|
|
ch <- i
|
2016-09-15 11:39:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
close(ch)
|
|
|
|
}(ch)
|
|
|
|
|
|
|
|
return ch
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Usage
|
|
|
|
|
|
|
|
```go
|
|
|
|
fmt.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
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println(100, "bottles of beer on the wall")
|
|
|
|
```
|