FAQ
I dislike how "break" is treated inside switches in Go.

Because Go did a good job at eliminating switch fall-through, one shouldn't
need the keyword break outside loops. So I'm confused that it still sees
use inside switches. I would think that more often than not, you want to
exit a loop based on a result you found inside the switch, rather than exit
the switch altogether.

The wiki <https://github.com/golang/go/wiki/Switch> gives this example:

command := ReadCommand()
argv := strings.Fields(command)
switch argv[0] {
case "echo":
     fmt.Print(argv[1:]...)
case "cat":
     if len(argv) <= 1 {
         fmt.Println("Usage: cat <filename>")
         break
     }
     PrintFile(argv[1])
default:
     fmt.Println("Unknown command; try 'echo' or 'cat'")
}

But why can we not do a simple if-else?

case "cat":
     if len(argv) <= 1 {
         fmt.Println("Usage: cat <filename>")
     } else {
         PrintFile(argv[1])
     }

I'll admit that such conflicts can be solved with labelled break and continue or (heaven forbid) goto. But I don't think such significant features should be necessary in this case. I'd also like to point out that it's inconsistent with "continue". A "continue" inside a switch inside a loop goes to the next iteration of the loop, but a "break" inside a switch inside a loop leaves the switch and does not interrupt execution of the loop. I think that "break" should stop the loop instead, because any control within the switch it offers can be accomplished by other control structures.

I'll also admit that I might have ignored a use case for breaks inside switch. If that's the case, perhaps a new keyword could be created, such as "stop" or "quit", to exit out of a switch, so that it consistently exits switches and "break" consistently exits loops?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 4 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedMar 24, '16 at 7:41a
activeMar 24, '16 at 12:05p
posts4
users4
websitegolang.org

People

Translate

site design / logo © 2022 Grokbase