英文:
Go - What is the equivalent of Python's "pass"?
问题
我在select语句中有一个默认的情况,我希望什么都不做,只是继续执行,但是将行留空会阻止语句中的任何操作发生。
select {
case quit_status := <-quit:
if quit_status == true {
fmt.Printf("********************* GOROUTINE [%d] Received QUIT MSG\n", id)
return
}
default:
fmt.Printf("GOROUTINE [%d] step: %d, NO QUIT MSG\n", id, i)
}
英文:
I have a default cause in a select statement that I want to do nothing, just continue, but leaving the line blank stops anything in the statement from happening
select {
case quit_status := <-quit:
if quit_status == true {
fmt.Printf("********************* GOROUTINE [%d] Received QUIT MSG\n", id)
return
}
default:
fmt.Printf("GOROUTINE [%d] step: %d, NO QUIT MSG\n", id, i)
}
答案1
得分: 10
default
语句在select
语句中用于提供非阻塞的通道读写操作。当所有的case中的通道都没有准备好进行读写时,会执行default
语句中的代码。
所以在你的情况下,如果退出通道没有任何消息,将会执行default
块。你可以简单地移除default
语句,这样它将会在quit_status := <-quit
这个case上阻塞,直到quit
中有一个值可用...这可能是你在这种情况下想要的。
如果你想要在select语句之后立即继续执行代码,你应该在一个单独的goroutine中运行这个select语句:
go func() {
select {
case quit_status := <-quit:
...
}
}()
// 立即在这里继续执行。
英文:
The default
case in a select
statement is intended to provide non-blocking I/O for channel reads and writes. The code in the default
case is executed whenever none of the channels in any of the cases are ready to be read/written to.
So in your case, the default
block is executed if the quit channel has nothing to say.
You can simply remove the default case and it will block on the quit_status := <-quit
case until a value is available in quit
.. which is probably what you are after in this instance.
If you want to immediately continue executing code after the select statement, you should run this select statement in a separate goroutine:
go func() {
select {
case quit_status := <-quit:
...
}
}()
// Execution continues here immediately.
答案2
得分: 3
正如@StephenWeinberg指出的那样,Go语言中没有pass语句。当通道接收到某个值时,可以在case中不做任何操作。
select {
case <-ch:
// 做一些操作
case <-time.After(2*time.Second):
// 超时
default:
// 什么都不做,即pass
}
英文:
As @StephenWeinberg pointed out, there is no pass statement in go. Simply put nothing in the case when the channel hits something.
select {
case <-ch:
// do something
case <-time.After(2*time.Second):
// timeout
default:
// do nothing aka pass
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论