forked from tmrts/go-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
concurrency/generator: refactor generator pattern
- Loading branch information
Showing
2 changed files
with
27 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) |