What benefit of break in switch statement? I mean labelled break is ok - for breaking outer loop. But simple break in switch is source of bugs, doesn’t it?
In golang, there is no break for switch however for loops it is necessary.
Really?
Switch with simple break https://play.golang.org/p/LXKpdi2EHpm
Switch with labeled break https://play.golang.org/p/o0xh4tNl7x7
First example loops forever, second is breaking loop.
Well, what benefit depends on the code, but it breaks the switch and that can be useful.
switch {
case something:
foo, err := whatever()
if err != nil {
break
}
fmt.Println(foo)
case somethingElse:
// ...
}
}
foo
isn’t printed if an error occurs. I could also imagine it as the opposite of fallthrough.
switch {
case something:
// processing processing
if notCommon {
break
}
fallthrough
case somethingElse:
// common stuff here
}
}
The something
case will continue into somethingElse
unless notCommon
is set. Making this too complicated is probably not a good idea, though.
I agree with @calmh, though there may be other use cases, the most natural is probably error checking and breaking instead of going further in the case if there was indeed an error.
@Tanmay_Shirsath, please read the specs when you are not sure before answering with wrong statements. A quick search is enough to get something like this: https://golang.org/ref/spec#Break_statements. Also, try things in the playground to be sure. Here’s a slightly modified example of Go Tour that shows how unlabeled break would work in a switch statement: https://play.golang.org/p/Ta7Qov-7uRD.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.