Go 为什么从未到达返回语句
请看下面的代码片段Go 为什么从未到达返回语句,go,Go,请看下面的代码片段 package main import ( "fmt" "time" ) func sender(ch chan string) { ch <- "Hello" ch <- "Foo" ch <- "and" ch <- "Boo" close(ch) } func main() { ch := make(chan string) go sender(ch)
package main
import (
"fmt"
"time"
)
func sender(ch chan string) {
ch <- "Hello"
ch <- "Foo"
ch <- "and"
ch <- "Boo"
close(ch)
}
func main() {
ch := make(chan string)
go sender(ch)
for {
select {
case value := <-ch:
fmt.Println(value)
case <-time.After(time.Second * 2):
fmt.Println("Return")
return
}
}
}
主程序包
进口(
“fmt”
“时间”
)
func发送器(ch chan字符串){
ch在for循环的每次迭代中都会创建一个新的两秒计时器。闭合通道始终准备好接收。代码永远循环,因为新计时器的通道在闭合通道准备好接收之前从未准备好接收
解决此问题的一种方法是将通道设置为零:
case value, ok := <-ch:
if !ok {
ch = nil
} else {
fmt.Println(value)
}
并在循环中的这一个计时器上选择:
after := time.After(time.Second * 2)
case <-after:
fmt.Println("Return")
return
如果您的程序打印在sender()
函数中发送的单词,然后继续打印空行,这是字符串的零值,从关闭的通道接收时返回此零值。请尝试删除关闭(ch)
看看会发生什么。封闭频道随时准备接收
这是什么意思?我每次都可以在封闭频道上接收?@zero\u coding我更新了句子,说封闭频道随时准备接收。换句话说,在封闭频道上接收永远不会阻塞。
case <-after:
fmt.Println("Return")
return