Switch Fallthrough in Go
If you are familar with C or Java, you must know that break
is requird for a switch's case branch, if break
is missed, then it will fall through to next case.
For example, consider the following code
Java
int a = 1;
switch (a) {
case 0: System.out.println("0");
case 1: System.out.println("1");
case 2: System.out.println("2"); break;
default: System.out.println("unknown"); break;
}
The output is:
This is because, we don't have break in case 1
, so it fall through to next branch case 2
Let's run the following golang code,
Go
var a = 1
switch a {
case 0:
fmt.Println("0")
case 1:
fmt.Println("1")
case 2:
fmt.Println("2")
default:
fmt.Println("unknown")
}
The output is 1
.
This is because, the golang switch doesn't require a break, if it reach to the end of the code of the case branch, it ends the execution. But how can we archive the fall through like Java?
Golang, provides a keyword fallthrough
, which supports to fall through to the next case branch.
Consider the following example,
Go
var a = 1
switch a {
case 0:
fmt.Println("0")
case 1:
fmt.Println("1")
fallthrough
case 2:
fmt.Println("2")
default:
fmt.Println("unknown")
}
The output is:
This is like what the above Java example.