程序从通道打印错误的变量。

huangapple go评论85阅读模式
英文:

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 &quot;fmt&quot;

func main() {

	c := make(chan int, 5)
	c &lt;- 5
	c &lt;- 6
	close(c)
	fmt.Println(&lt;-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"

https://golangr.com/close-channel/

huangapple
  • 本文由 发表于 2022年2月15日 16:36:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/71123302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定