Switch in Go

Contents
Switch on a value
No fallthrough by default
Switch with initializer
Type switches

Switch on a value

A switch compares one value against a list of cases and runs the first case that matches. It reads better than a long chain of if and else if statements when every branch tests the same value.

package main import "fmt" func main() { day := 3 switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") default: fmt.Println("Another day") } }

go run main.go

Wednesday

The default branch runs when no case matches. It is optional, but adding it documents what should happen with unexpected input.

No fallthrough by default

Unlike C, Go cases do not fall through into the next case. When a case body finishes, the whole switch ends, so you never need a break at the end of a case.

package main import "fmt" func main() { day := 6 switch day { case 6, 7: fmt.Println("Weekend") case 1: fmt.Println("Monday") default: fmt.Println("Workday") } }

One case can list several comma separated values, which keeps weekday and weekend style groupings short. The rare fallthrough keyword exists for the exceptional situation when the next case body must run as well, but most programs never use it.

Switch with initializer

Like an if statement, a switch can declare a short lived variable right in its header. The variable exists only inside the switch, which keeps the surrounding scope clean.

package main import "fmt" func main() { switch n := 7 % 2; n { case 0: fmt.Println("Even") default: fmt.Println("Odd") } }

A switch without any tag value is also legal: it behaves like a tidy if and else chain where each case holds a condition. Use the tagged form for values and the untagged form for conditions.

Type switches

A type switch inspects the dynamic type of an interface value instead of its content. Each case names a type, and inside that case the switched variable already has the concrete type.

package main import "fmt" func main() { var v any = "hello" switch t := v.(type) { case int: fmt.Println("int:", t) case string: fmt.Println("string:", t) default: fmt.Println("unknown type") } }

Type switches are the classic way to handle values of unknown shape, for example decoded data fields or plugin arguments. Keep the default branch so new types fail loudly instead of silently.

Next: Loops with for

Article author: Arthur Isaev

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: