英文:
How to get a value from a channel without waiting for it
问题
在Go语言中,如果我尝试从一个通道接收数据,程序的执行将会停止,直到通道中有值为止。然而,我想要做的是让程序继续执行,并且如果通道中有值,对其进行操作。
我心中的伪代码大致如下:
mychan := make(chan int, 1)
go someGoRoutine(mychan) // 这可能会在某个时刻向mychan中放入一些值
for {
if "mychan"中有值 {
// 从"mychan"中移除元素并进行处理
} else {
// 其他代码
}
}
据我了解,我不能简单地使用v <- mychan
,因为这会阻塞程序的执行,直到有值可用。在Go语言中,应该如何实现这个功能呢?
英文:
In Go, if I try to receive from a channel, the program's execution is going to be stopped until some value is in the channel. However, what I would like to do is let the program execution continue and, if there's a value in the channel, act on it.
The pseudo-code I have in mind is something like this:
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
}
}
As I understand, I cannot simply use v <- mychan
because that would block the program execution until a value is available. What would be the way to do this in Go?
答案1
得分: 8
那就是 select 的作用。例如:
for {
select {
case v := <-c1:
// 处理 v
case v, ok := <-c2:
// 第二种形式,'!ok' -> c2 已关闭
default:
// 接收未完成
}
}
英文:
That's what select is for. For example:
for {
select {
case v := <-c1:
// process v
case v, ok := <-c2:
// Second form, '!ok' -> c2 was closed
default:
// receiving was not done
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论