Go开关/外壳是否掉线? [英] Do Go switch/cases fallthrough or not?

查看:69
本文介绍了Go开关/外壳是否掉线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您到达Go案例的结尾时,会发生这种情况吗?是发生在下一个案例中还是假设大多数应用程序都不希望出现这种情况?

What happens when you reach the end of a Go case, does it fall through to the next, or assume that most applications don't want to fall through?

推荐答案

否,默认情况下,Go switch语句不会掉线.如果要做要使其失败,则必须显式使用"fallthrough"语句.从规范:

No, Go switch statements do not fall through by default. If you do want it to fallthrough, you must explicitly use a "fallthrough" statement. From the spec:

在case或default子句中,最后一个非空语句可以是 (可能带有标签)"fallthrough"语句来表示该控件 应该从本节的末尾流到 下一个子句.否则,控制流到开关"的末尾 陈述. "fallthrough"语句可能显示为最后一条语句 除表达式开关的最后一个子句之外的所有子句.

In a case or default clause, the last non-empty statement may be a (possibly labeled) "fallthrough" statement to indicate that control should flow from the end of this clause to the first statement of the next clause. Otherwise control flows to the end of the "switch" statement. A "fallthrough" statement may appear as the last statement of all but the last clause of an expression switch.

例如(对不起,我无法为自己的生活想到一个真实的例子):

For example (sorry, I could not for the life of me think of a real example):

switch 1 {
case 1:
    fmt.Println("I will print")
    fallthrough
case 0:
    fmt.Println("I will also print")
}

https://play.golang.org/p/va6R8Oj02z

这篇关于Go开关/外壳是否掉线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆