英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论