英文:
Program printing the wrong variable from channel
问题
package main
import "fmt"
func main() {
c := make(chan int, 5)
c <- 5
c <- 6
close(c)
fmt.Println(<-c)
}
上面的程序应该打印出6,因为它是发送到通道的最后一个值,为什么会打印出5呢?
另外,从已关闭的通道接收/打印是可能的吗?
它打印出5。
英文:
package main
import "fmt"
func main() {
c := make(chan int, 5)
c <- 5
c <- 6
close(c)
fmt.Println(<-c)
}
shouldn't the program above print 6 since it is the last value sent to the channel?
Whay is more, is it possible to print / receiving from a closed channel?
It prints 5
答案1
得分: 3
Golang的通道是先进先出(FIFO)的。这就是为什么数字5会先被打印出来。
编辑:关闭通道表示不会再向其发送数据。
> "如果一个通道被关闭,你仍然可以读取数据。但是你不能向其中发送新数据。这个程序在关闭通道之前和之后都进行了读取,这是有效的。它只是关闭了发送操作"
https://golangr.com/close-channel/
英文:
Golang channels are FIFO, first in first out. That is why 5 gets printed out first.
EDIT: Closing channel indicates that no more data will be send to it.
> "If a channel is closed, you can still read data. But you cannot send
> new data into it. This program reads both before and after closing the
> channel, which works. It’s closed only for sending"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论