/*
* The Go switch statement.
*/
package main
import "fmt"
func main() {
tot := 0
for keepon := true ; keepon ; {
// Prompt and read two items from the line.
fmt.Printf("==> ");
var cmd, arg string
num, err := fmt.Scanln(&cmd, &arg)
// Get the numerical equivent of the arg
count := 1
if num == 2 {
num, err = fmt.Sscan(arg, &count)
if err != nil {
count = 1
}
}
switch cmd {
case "boring":
fmt.Printf("boring")
for i := 1 ; i < count ; i++ {
fmt.Printf(" boring")
}
fmt.Printf("\n")
case "add":
tot += count
fmt.Printf("Tot is %d\n", tot)
case "say":
fmt.Printf("You told me %s\n", arg)
case "sink":
fmt.Printf("#%d is down! Blub blub blub\n", count)
case "stop", "quit", "halt":
if count > 0 {
if count > 1 {
fmt.Printf("Sorry, can only stop " +
"once\n");
}
keepon = false
}
default:
fmt.Printf("Unknown command %s\n", cmd)
}
}
}
The switch statment compares an expression to cases as we're used to.
Several differences from C, C++ and Java:
- Cases break automatically at the next case.
- A case may list several values, any of which can match.
- The type of the expression
is not limited to simple types (as C and C++) or simple types or
strings (Java).
- Values need not be unique. The first match wins.