Ryan
Ryan

Reputation: 23

Go channel infinite loop not block

I am reading 8.5 chapter of The Go Programming Language, and get in stuck for some code. code list below.

func main() {

    naturals := make(chan int)
    squares := make(chan int)

    // Counter
    go func() {
        for x := 0; x <= 5; x++ {
            naturals <- x
        }
        close(naturals)
    }()

    // Squarer
    go func() {
        for v := range naturals {
            squares <- v * v
        }

        close(squares)
    }()

    // for x := range squares {
    //  fmt.Println(x)
    // }
    // OUTPUT(correct):
    // 0
    // 1
    // 4
    // 9
    // 16
    // 25

    // for y := 0; y <= 5; y++ {
    //  fmt.Println(<-squares)
    // }
    // OUTPUT(correct):
    // 0
    // 1
    // 4
    // 9
    // 16
    // 25

    // for {
    //  fmt.Println(<-squares)
    // }
    // OUTPUT(incorrect):
    // 0
    // 0
    // 0
    // 0
    // 0
    // 0
    // ...

}

I can understand how the First 2 work, but the 3rd one seem to be out of expect.

So my question is why 3rd print function not block, and always print 0.

Upvotes: 0

Views: 415

Answers (1)

Schwern
Schwern

Reputation: 165208

The output of the 3rd loop is...

0
1
4
9
16
25
0
0
0

And so on. It just looks like nothing but zeros because the first numbers have scrolled off the screen.

Reading from a closed channel results in zero of the channels type. This is an int channel in an infinite loop, so you get infinite 0's.

Upvotes: 1

Related Questions