猿问

如何在不等待的情况下从通道获取值

在 Go 中,如果我尝试从通道接收,程序的执行将停止,直到通道中存在某个值。但是,我想做的是让程序继续执行,如果通道中有值,则对其进行操作。


我想到的伪代码是这样的:


mychan := make(chan int, 1)


go someGoRoutine(mychan) // This might put some value in mychan at some point


for {

    if something in "mychan" {

        // Remove the element from "mychan" and process it

    } else {

        // Other code

    }

}

据我了解,我不能简单地使用,v <- mychan因为这会阻止程序执行,直到值可用。在 Go 中这样做的方法是什么?


Smart猫小萌
浏览 175回答 1
1回答

侃侃无极

这就是选择的用途。例如:for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case v := <-c1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // process v&nbsp; &nbsp; &nbsp; &nbsp; case v, ok := <-c2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Second form, '!ok' -> c2 was closed&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // receiving was not done&nbsp; &nbsp; &nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答