Go channel:从 channel 消费数据,但不向 channel 推送任何内容

Go channel: consume data from channel although not push anything to channel

例如我有这个代码:

package main

import (
    "fmt"
)

func main() {

    c1 := make(chan interface{})
    close(c1)
    c2 := make(chan interface{})
    close(c2)

    var c1Count, c2Count int
    for i := 1000; i >= 0; i-- {
        select {
        case <-c1:
            c1Count++
        case <-c2:
            c2Count++
        }

    }
    fmt.Printf("c1Count: %d\nc2Count: %d\n  ", c1Count, c2Count)
}

当运行时,输出将是:

c1Count: 513
c2Count: 488

我不知道的是:我们创建了 c1 和 c2 通道而没有做任何事情。为什么在select/case块中,c1Count和c2Count可以增加值?

谢谢

The Go Programming Language Specification

Close

After calling close, and after any previously sent values have been received, receive operations will return the zero value for the channel's type without blocking. The multi-valued receive operation returns a received value along with an indication of whether the channel is closed.


您计算的是零值。

例如,

package main

import (
    "fmt"
)

func main() {

    c1 := make(chan interface{})
    close(c1)
    c2 := make(chan interface{})
    close(c2)

    var c1Count, c2Count int
    var z1Count, z2Count int
    for i := 1000; i >= 0; i-- {
        select {
        case z1 := <-c1:
            c1Count++
            if z1 == nil {
                z1Count++
            }

        case z2 := <-c2:
            c2Count++
            if z2 == nil {
                z2Count++
            }
        }

    }
    fmt.Printf("c1Count: %d\nc2Count: %d\n", c1Count, c2Count)
    fmt.Printf("z1Count: %d\nz2Count: %d\n", z1Count, z2Count)
}

游乐场:https://play.golang.org/p/tPRkqXrAFno

输出:

c1Count: 511
c2Count: 490
z1Count: 511
z2Count: 490

The Go Programming Language Specification

For statements

For statements with range clause

For channels, the iteration values produced are the successive values sent on the channel until the channel is closed. If the channel is nil, the range expression blocks forever.

Close 对于带有范围子句的 for 语句很有用。