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?

有帮助吗?

解决方案

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
        }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top