Reputation: 1265
Here is the code example in "A Tour of Go" Range and Close:
package main
import (
"fmt"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
}
On the fifth line from the bottom, when the go
keyword was omitted, the result did not change. Did that mean the main goroutine sent values in the buffered channel and then took them out?
Upvotes: 4
Views: 1230
Reputation: 18607
You can think of it like this:
With the go
keyword, the fibonacci
function is adding numbers onto the channel and the for i := range c
loop is printing each number out as soon as it is added to the channel.
Without the go
keyword, the fibonacci
function is called, adds all the numbers to the channel, and then returns, and then the for
loop prints the numbers off the channel
.
One good way to see this is to put in a sleep (playground link):
package main
import (
"fmt"
"time"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
time.Sleep(time.Second) // ADDED THIS SLEEP
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c) // TOGGLE BETWEEN THIS
// fibonacci(cap(c), c) // AND THIS
for i := range c {
fmt.Println(i)
}
}
Upvotes: 2