Go by Example: Switch [Link]
com/switch
Go by Example: Switch
Switch statements express conditionals across
many branches.
package main
import (
"fmt"
"time"
)
func main() {
Here’s a basic switch. i := 2
[Link]("Write ", i, " as ")
switch i {
case 1:
[Link]("one")
case 2:
[Link]("two")
case 3:
[Link]("three")
}
You can use commas to separate multiple switch [Link]().Weekday() {
expressions in the same case statement. We use case [Link], [Link]:
the optional default case in this example as well. [Link]("It's the weekend")
default:
[Link]("It's a weekday")
}
switch without an expression is an alternate way t := [Link]()
to express if/else logic. Here we also show how the switch {
case expressions can be non-constants. case [Link]() < 12:
[Link]("It's before noon")
default:
[Link]("It's after noon")
}
A type switch compares types instead of values. whatAmI := func(i interface{}) {
You can use this to discover the type of an switch t := i.(type) {
interface value. In this example, the variable t will case bool:
[Link]("I'm a bool")
have the type corresponding to its clause.
case int:
[Link]("I'm an int")
default:
[Link]("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}
$ go run [Link]
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string
Next example: Arrays.
by Mark McGranaghan and Eli Bendersky | source | license
1 of 1 11/26/24, 23:27