gpt4 book ai didi

转到 channel : consume data from channel although not push anything to channel

转载 作者:IT王子 更新时间:2023-10-29 01:34:27 29 4
gpt4 key购买 nike

例如我有这段代码:

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 channel 。为什么在 select/case block 中,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)
}

Playground :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 语句很有用。

关于转到 channel : consume data from channel although not push anything to channel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54265982/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com