Go – Duplicate case in switch statement

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

Go - Duplicate case in switch statement

问题

我刚开始学习Go语言,在尝试消除一些重复的代码时,我添加了一个带有fallthrough的case,代码如下:

i := 1
switch i {
case 0, 1:
    fmt.Println("common code")
    fallthrough
case 0:
    fmt.Println("aux for 0")
case 1:
    fmt.Println("aux for 1")
default:
    fmt.Println("other number")
}

然而,我收到了关于重复case的错误提示,如下所示:

prog.go:13: duplicate case 0 in switch
    previous case at prog.go:10
prog.go:15: duplicate case 1 in switch
    previous case at prog.go:10

为什么会出现这个错误?有没有办法告诉编译器允许这样的代码?

英文:

I am new to Go, and while attempting to remove some duplicate code across switch statements I added a case with fallthrough like so:

i := 1
switch i {
case 0, 1:
    fmt.Println("common code")
    fallthrough
case 0:
    fmt.Println("aux for 0")
case 1:
    fmt.Println("aux for 1")
default:
    fmt.Println("other number")

}

However, I received an error about the duplicate cases such as:

prog.go:13: duplicate case 0 in switch
    previous case at prog.go:10
prog.go:15: duplicate case 1 in switch
    previous case at prog.go:10

Why is this an error? Is there some way to instruct the compiler to allow such code?

答案1

得分: 4

这种行为在当前的Go语言中是因为switch语句的实现方式类似于if-else-if。显然,if (1) else if (1)是没有意义的,因此会出现这个错误。

目前,没有办法强制编译器执行这种操作。你需要重新编写语句以达到你想要的效果。

根据这个据称引用了Rob Pike的错误报告评论,这个限制将在未来的Go版本中解除。

英文:

The reason for this behavior, in the current Go, is that the switch is implemented like an if-else-if. Obviously, if (1) else if (1) doesn't make sense, thus you get this error.

Right now, there is no way to force the compiler to do this. You have to rewrite your statements to get the effect you want.

Per this bug report comment supposedly quoting Rob Pike, this restriction will be lifted in a future Go version.

答案2

得分: 0

每个值只能有一个case语句,所以这段代码是非法的。此外,fallthrough只能起作用一次,所以即使它对于0按照你的期望工作了,对于1仍然会失败。

最简单的解决方案是将初始的0和1的case放在主switch之前的一个单独的switch或if语句中。

英文:

You can only have one case statement for each value, so that code is illegal. Additionally, fallthrough only works once, so even if it worked as you wanted for 0, it would still fail for 1.

The simplest solution is to put the initial 0,1 case in its own switch or if before the main switch.

huangapple
  • 本文由 发表于 2014年4月3日 07:15:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/22824917.html
匿名

发表评论

匿名网友

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

确定