Ad space (banner)
๐ŸนGo Lessons
Lesson 14 / 68

The switch Statement

In this lesson you will learn how to branch on several values with a switch statement in Go, which reads more clearly than a chain of if statements. This is for anyone searching for "Go switch statement how to use".

Go has a switch statement too. Unlike most other languages, execution does not fall through into the next case, so you never have to write break at the end of each one.

The sample code prints a different message for case 1 through case 3 depending on day, falling back to "Other day" in default. Go's designers judged the C and JavaScript fall-through behaviour to be an easy source of accidental bugs, and made the safe option the default.

A common stumbling block for beginners is writing break every time out of habit from another language. It is unnecessary in Go, and conversely, when you genuinely do want execution to continue into the next case, you have to say so explicitly with fallthrough.

In real-world development switch statements are common wherever you branch on a fixed set of options, such as days of the week or status codes.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)