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 C# 调用Bartender打印机打印
  • ¥100 华为ensp只要2-9实验运行结果能做的来加我QQ
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。
  • ¥15 已知隐函数其中一个变量τ的具体值,求另一个变量
  • ¥15 r语言Hurst指数
  • ¥15 Acrn IVSHMEM doorbell问题
  • ¥15 yolov5中的val测试集训练时数量变小问题
  • ¥15 MPLS/VPN实验中MPLS的配置问题