dsds33222 2014-04-02 23:15
浏览 79


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")
case 0:
    fmt.Println("aux for 0")
case 1:
    fmt.Println("aux for 1")
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 请专家看看这个问题出在哪里?
  • ¥15 tensorrt 推理 yolov8框出现错误
  • ¥15 用hc 05,做蓝牙控制小车 小车只能说初始遥控方向影响,后续不能更改
  • ¥15 51单片机怎么把每次输入键值保存到数组作为我的确认键的判断条件呢
  • ¥15 c语言字符串单词入门问题报错
  • ¥30 我现在是双非人工智能专业不知道要不要转到软件工程专业
  • ¥15 请问12脉波整流机组的外特性曲线具体是如何推导
  • ¥15 abaqus里的python算法
  • ¥100 如何在思科模拟器中进入CEF模式
  • ¥15 Simulink 仿真如何使用MATLAB function模块获取到仿真过程中某一仿真时刻输入到模块的函数的值?