-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
34 lines (30 loc) · 823 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
import "fmt"
// main demonstrates how a channel can be used to retrieve
// values one at a time, limiting the memory usage.
func main() {
g := generator(10, 20)
for i := range g {
fmt.Println(i)
}
}
// generator yields the integers between start (inclusive)
// and end (exclusive) through the channel it returns.
func generator(start, end int) <-chan int {
/*
A new channel is created (unbuffered) in this case as
the receiver is looking one number at a time.
A goroutine is responsible for sending the numbers in
and defering the channel close when finished.
This allows the range loop on line #7 to iterate all
values and stop iterating when all have been processed.
*/
c := make(chan int)
go func() {
defer close(c)
for i := start; i < end; i++ {
c <- i
}
}()
return c
}