我怎样才能做类似下面的事情?:
func foo(input <-chan char, output chan<- string) {
var c char
var ok bool
for {
if ThereAreValuesBufferedIn(input) {
c, ok = <-input
} else {
output <- "update message"
c, ok = <-input
}
DoSomethingWith(c, ok)
}
}
基本上,我想检查 chan 中是否有缓冲值,如果没有,我可以在线程被阻塞之前发送更新消息。
最佳答案
package main
func foo(input <-chan char, output chan<- string) {
for {
select {
case c, ok := <-input:
if ok { // ThereAreValuesBufferedIn(input)
... process c
} else { // input is closed
... handle closed input
}
default:
output <- "update message"
c, ok := <-input // will block
DoSomethingWith(c, ok)
}
}
}
编辑:修复了作用域错误。
关于go - 有什么方法可以检查值是否缓冲在 Go chan 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17951344/