Go – Python的”pass”的等价物是什么?

huangapple go评论100阅读模式
英文:

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 := &lt;-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 := &lt;-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 &lt;-ch:
		// do something
	case &lt;-time.After(2*time.Second):
        // timeout
    default:
        // do nothing aka pass
}

huangapple
  • 本文由 发表于 2012年9月17日 09:48:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/12452254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定