Go switch/cases 是否会失败? [英] Do Go switch/cases fallthrough or not?

查看:19
本文介绍了Go switch/cases 是否会失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你到达一个 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 语句默认不会通过.如果您确实希望它失败,则必须明确使用失败"语句.来自 规范:

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"语句可能作为最后一个语句出现除了表达式 switch 的最后一个子句之外的所有子句.

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 switch/cases 是否会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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