1

go 通道输出结果问题

 2 years ago
source link: https://www.v2ex.com/t/809873
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
go 通道输出结果问题

V2EX  ›  Go 编程语言

go 通道输出结果问题

  Grocker · 6 小时 11 分钟前 · 473 次点击
package main

import (
    "fmt"
)

func main() {
    c := make(chan int, 5)
    c <- 5
    c <- 6
    close(c)
    fmt.Println(<-c)
}

这段代码输出的结果为什么是 5 ?没太看明白

12 条回复    2021-10-23 00:05:46 +08:00

labulaka521

labulaka521   6 小时 3 分钟前

先进先出
5 进去了 6 进去了-> 5 出来了 6 出来了

dugoj

dugoj   6 小时 1 分钟前

类似先入先出的 FIFO 队列,你再 print 一下就是 6 了,或者 for range 遍历一下

keepeye

keepeye   5 小时 59 分钟前

队列啊 先进先出

Keystroke

Keystroke   5 小时 56 分钟前 via Android

我猜你是想问为什么 close 了还会接收到 5 而不是 0 。
因为接收操作的底层逻辑是先 qcount > 0,即缓冲队列是否还有元素。再判断 closed != 0,即管道是否关闭。所以,5 和 6 取出后才是 0 。

Keystroke

Keystroke   5 小时 55 分钟前 via Android

好像是我想多了。

labulaka521

labulaka521   5 小时 46 分钟前

For a channel c, the built-in function close(c) records that no more values will be sent on the channel. 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.
@Keystroke

https://golang.org/ref/spec#Close

Keystroke

Keystroke   5 小时 24 分钟前 via Android

@labulaka521
我说的不是一个意思吗?

xfriday

xfriday   3 小时 13 分钟前

@Keystroke chan 关闭了取出来的是零值,如果要判断 chan 是不是已经关闭了,可以这样:
r, ok := <- c
if ok {
// ..
}

Keystroke

Keystroke   2 小时 50 分钟前 via Android

@xfriday
你先去试试楼主的代码最后一句改成你说的样子。看看 ok 是 true 还是 false 。

xfriday

xfriday   18 分钟前

@Keystroke 当然是 true 啊,chan 里的数据有没用取完

Keystroke

Keystroke   8 分钟前 via Android

@xfriday 那跟我最开始的回答不是一个意思吗?

关于   ·   帮助文档   ·   FAQ   ·   API   ·   我们的愿景   ·   广告投放   ·   感谢   ·   实用小工具   ·   1967 人在线   最高记录 5497   ·  

创意工作者们的社区

World is powered by solitude

VERSION: 3.9.8.5 · 17ms · UTC 16:14 · PVG 00:14 · LAX 09:14 · JFK 12:14
♥ Do have faith in what you're doing.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK