dsds33222 2014-04-02 23:15
浏览 79
已采纳

Go-switch语句中的重复大小写

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?

  • 写回答

2条回答 默认 最新

  • dpgf42422 2014-04-02 23:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog