I'm learning Go langue in here, and I modify a little code like this, I add a sleep(2s) before quit <- 0
, and output index of fibonacci with i
, below is my code:
package main
import "fmt"
import "time"
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(i,<-c) // output index for result clearly
}
time.Sleep(2000*time.Millisecond) // add sleep for result clearly
quit <- 0
}()
fibonacci(c, quit)
}
I find the stdout output 0-8 immediately, but wait 2 seconds it output 9th and then is "quit".
I move this code to a single go file and run it. At first it output 0-8 like above described, but after I change total number (from 10 to 9,8 or 3, whatever) some times, it output directly all fibonacci number immediately as I was excepted (of course it output quit
after 2 seconds)!
I run the code in the browser (I used Chrome) it still output 9th delay, when I change 10 to 3, it output 0-2 immediately.
So I'm confused why does it output 9th delay?
UPDATE: I think I know why, because my output window too small to output whole result, but I always scroll down all time it still display 8th. If I scale output window larger, it will output 0-9 immediately. So is it a bug of this tutorial?
I think it is a bug of this tutorial. If the output window (left-bottom) is too small, it will display without the last line, so the 9th won't be display immediately.
if I add fmt.Println("foo")
after fmt.Println(i,<-c)
, it won't output the last line contains foo
string, but the 9th fibonacci will be displayed.
I capture the response in Chrome, it can tell how to display the result including what time it will output. So it must be a bug of page that swallow the last line. :D
PS: The response like this:
{
"Errors":"",
"Events":[
{
"Message":"0 0
foo
1 1
foo
2 1
foo
3 2
foo
4 3
foo
5 5
foo
6 8
foo
7 13
foo
8 21
foo
9 34
foo
",
"Kind":"stdout",
"Delay":0
},
{
"Message":"quit
",
"Kind":"stdout",
"Delay":2000000000
}
]
}