Skip to content

Commit 89df9f0

Browse files
mehdytmrts
authored andcommitted
concurrency/generator: refactor generator pattern
1 parent d05638a commit 89df9f0

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

concurrency/generator.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package generator
2+
3+
func Range(start int, end int, step int) chan int {
4+
c := make(chan int)
5+
6+
go func() {
7+
result := start
8+
for result < end {
9+
c <- result
10+
result = result + step
11+
}
12+
13+
close(c)
14+
}()
15+
16+
return c
17+
}
18+
19+
func main() {
20+
// print the numbers from 3 through 47 with a step size of 2
21+
for i := range Range(3, 47, 2) {
22+
println(i)
23+
}
24+
}

concurrency/generator.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Generator Pattern
22

3-
[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.
3+
[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time
44

55
# Implementation and Example
6-
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).
6+
7+
You can find the implementation and usage in [generator.go](generator.go)

0 commit comments

Comments
 (0)