mirror of
https://github.com/tmrts/go-patterns.git
synced 2024-11-24 14:06:06 +03:00
concurrency/generator: refactor generator pattern
This commit is contained in:
parent
d05638adac
commit
89df9f0955
24
concurrency/generator.go
Normal file
24
concurrency/generator.go
Normal file
@ -0,0 +1,24 @@
|
||||
package generator
|
||||
|
||||
func Range(start int, end int, step int) chan int {
|
||||
c := make(chan int)
|
||||
|
||||
go func() {
|
||||
result := start
|
||||
for result < end {
|
||||
c <- result
|
||||
result = result + step
|
||||
}
|
||||
|
||||
close(c)
|
||||
}()
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func main() {
|
||||
// print the numbers from 3 through 47 with a step size of 2
|
||||
for i := range Range(3, 47, 2) {
|
||||
println(i)
|
||||
}
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
# Generator Pattern
|
||||
|
||||
[Generator](https://en.wikipedia.org/wiki/Generator_(computer_programming)) is a special routine that can be used to control the iteration behavior of a loop.
|
||||
[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time
|
||||
|
||||
# Implementation and Example
|
||||
With Go language, we can implement generator in two ways: channel and closure. Fibonacci number generation example can be found in [generators.go](generators.go).
|
||||
|
||||
You can find the implementation and usage in [generator.go](generator.go)
|
||||
|
Loading…
Reference in New Issue
Block a user