Movatterモバイル変換


[0]ホーム

URL:


5 switch statement patterns

yourbasic.org/golang

Basic switch with default

switch time.Now().Weekday() {case time.Saturday:fmt.Println("Today is Saturday.")case time.Sunday:fmt.Println("Today is Sunday.")default:fmt.Println("Today is a weekday.")}

Unlike C and Java, the case expressions do not need to be constants.

No condition

A switch without a condition is the same as switch true.

switch hour := time.Now().Hour(); {// missing expression means "true"case hour< 12:fmt.Println("Good morning!")case hour< 17:fmt.Println("Good afternoon!")default:fmt.Println("Good evening!")}

Case list

func WhiteSpace(c rune) bool {    switch c {case ' ', '\t', '\n', '\f', '\r':        return true    }    return false}

Fallthrough

switch 2 {case 1:fmt.Println("1")fallthroughcase 2:fmt.Println("2")fallthroughcase 3:fmt.Println("3")}
23

Exit with break

Abreak statement terminates execution of theinnermostfor,switch, orselect statement.

If you need to break out of a surrounding loop, not the switch, you can put alabelon the loop and break to that label. This example shows both uses.

Loop:for _, ch := range "a b\nc" {switch ch {case ' ':// skip spacebreakcase '\n':// break at newlinebreak Loopdefault:fmt.Printf("%c\n", ch)}}
ab

Execution order

// Foo prints and returns n.func Foo(n int) int {fmt.Println(n)return n}func main() {switch Foo(2) {case Foo(1), Foo(2), Foo(3):fmt.Println("First case")fallthroughcase Foo(4):fmt.Println("Second case")}}
212First caseSecond case

Go step by step

Core Go concepts:interfaces,structs,slices,maps,for loops,switch statements,packages.

Related

Switch
Effective Go
4 basic if-else statement patterns
If statements in Go can include an init statement. Go has no short one-line alternative to the question mark operator.
yourbasic.org
Select waits on a group of channels
A select statement allows you to wait for multiple send or receive operations simultaneously.
yourbasic.org

Most Read

See all 178 Go articles


[8]ページ先頭

©2009-2025 Movatter.jp