From f3daa894afefb443a08a04217dbac38fcdb9b2c6 Mon Sep 17 00:00:00 2001 From: Jian Han Date: Sun, 3 Dec 2017 20:23:59 +1000 Subject: [PATCH] added iterator --- concurrency/iterator/main.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 concurrency/iterator/main.go diff --git a/concurrency/iterator/main.go b/concurrency/iterator/main.go new file mode 100644 index 0000000..31ac7fe --- /dev/null +++ b/concurrency/iterator/main.go @@ -0,0 +1,24 @@ +package main + +import "fmt" + +// Generator func which produces data which might be computationally expensive. +func fib(n int) chan int { + c := make(chan int) + go func() { + for i, j := 0, 1; i < n; i, j = i+j, i { + c <- i + } + close(c) + }() + return c +} + +func main() { + // fib returns the fibonacci numbers lesser than 1000 + for i := range fib(1000) { + // Consumer which consumes the data produced by the generator, which further does some extra computations + v := i * i + fmt.Println(v) + } +}