kwarrick
kwarrick

Reputation: 6240

Go - Duplicate case in switch statement

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?

Upvotes: 1

Views: 3319

Answers (2)

bishop
bishop

Reputation: 39444

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.

Upvotes: 4

Evan
Evan

Reputation: 6545

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.

Upvotes: 0

Related Questions