This question already has an answer here:
I'm new to Golang and I found that the switch case
statement doesn't need a break
statement to stop evaluating the cases.
So, I wanna know how to implement this fallthrough behavior in go?
</div>
There is exactly a fallthrough
statement for this.
See this example:
fmt.Println("First round: without fallthrough")
switch 1 {
case 0:
fmt.Println(0)
case 1:
fmt.Println(1)
case 2:
fmt.Println(2)
case 3:
fmt.Println(3)
}
fmt.Println("Second round: with fallthrough")
switch 1 {
case 0:
fmt.Println(0)
fallthrough
case 1:
fmt.Println(1)
fallthrough
case 2:
fmt.Println(2)
fallthrough
case 3:
fmt.Println(3)
}
Output (try it on the Go Playground):
First round: without fallthrough
1
Second round: with fallthrough
1
2
3
(Note that I did not use a fallthrough
statement in the last case
, as that would be a compile time error: "cannot fallthrough final case in switch".)