Go Switch Statement
A Go switch statement evaluates an expression or a sequence of conditions and executes the first matching case. It is often clearer than a long chain of if and else if statements when the program must choose between several alternatives.
Go supports expression switches, condition-based switches, multiple values in one case, short initialization statements, type switches, and the explicit fallthrough keyword.
Go Switch with an Expression
The syntax of Switch statement with expression right after the switch keyword is
switch expression {
case value1:
statement(s)
case value2:
statement(s)
default:
statement(s)
}
where switch, case and default are the keywords. expression should evaluate to a value of type as that of the case values.
There could be multiple case blocks. The default block is optional. If no case value matches the expression‘s value, the default block is executed.
Go evaluates cases from top to bottom and stops after the first matching case. Unlike switches in several other languages, Go does not require a break statement at the end of each case.
Go Switch Example with Integer Cases
In the following example, we have taken a simple expression of a variable today. Based on its value, we are printing what day of the week it is using switch statement.
example.go
package main
import "fmt"
func main() {
var today int = 2
switch today {
case 1:
fmt.Printf("Today is Monday")
case 2:
fmt.Printf("Today is Tuesday")
case 3:
fmt.Printf("Today is Wednesday")
case 4:
fmt.Printf("Today is Thursday")
case 5:
fmt.Printf("Today is Friday")
case 6:
fmt.Printf("Today is Saturday")
case 7:
fmt.Printf("Today is Sunday")
default:
fmt.Printf("Value for today is invalid.")
}
}
Output
Today is Tuesday
Because today contains 2, the second case matches and its statement is executed. The remaining cases are skipped.
Go Switch without an Expression
You can also write switch statement without expression mentioned right after the switch keyword.
The syntax of switch statement without expression is
switch {
case expression1==value1:
statement(s)
case expression2==value2:
statement(s)
default:
statement(s)
}
where switch, case and default are the keywords. The expression can vary from case to case.
An expressionless switch behaves like switch true. Each case contains a Boolean condition, and the first condition that evaluates to true is selected.
Go Switch Example with Boolean Conditions
In the following example, we have taken the expression to case blocks. We have used the same expression for all cases, but we can use a different expression for any of the case block(s).
example.go
package main
import "fmt"
func main() {
var today int = 4
switch {
case today==1:
fmt.Printf("Today is Monday")
case today==2:
fmt.Printf("Today is Tuesday")
case today==3:
fmt.Printf("Today is Wednesday")
case today==4:
fmt.Printf("Today is Thursday")
case today==5:
fmt.Printf("Today is Friday")
case today==6:
fmt.Printf("Today is Saturday")
case today==7:
fmt.Printf("Today is Sunday")
default:
fmt.Printf("Value for today is invalid.")
}
}
Output
Today is Thursday
Go Switch with Multiple Values in One Case
A single Go case can list multiple comma-separated values. The case runs when the switch expression matches any value in that list.
package main
import "fmt"
func main() {
day := "Saturday"
switch day {
case "Saturday", "Sunday":
fmt.Println("Weekend")
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
fmt.Println("Weekday")
default:
fmt.Println("Invalid day")
}
}
Output
Weekend
This form avoids repeating the same statements in separate cases that represent the same category.
Go Switch Case with String Values
Switch expressions are not limited to integers. The following example matches a command stored in a string.
package main
import "fmt"
func main() {
command := "start"
switch command {
case "start":
fmt.Println("Starting service")
case "stop":
fmt.Println("Stopping service")
case "restart":
fmt.Println("Restarting service")
default:
fmt.Println("Unknown command")
}
}
Output
Starting service
String comparisons in a Go switch are case-sensitive, so "start" and "Start" are different values.
Go Switch with a Short Initialization Statement
A Go switch may include a short statement before the expression. The initialized variable is scoped to the switch statement and its cases.
switch initialization; expression {
case value1:
statements
case value2:
statements
default:
statements
}
package main
import "fmt"
func main() {
switch length := len("Golang"); length {
case 0:
fmt.Println("Empty string")
case 1, 2, 3:
fmt.Println("Short string")
default:
fmt.Println("String length:", length)
}
}
Output
String length: 6
The variable length is available inside every case but is not available after the switch ends.
Go Switch Does Not Need Break
Go automatically exits a switch after executing a matching case. Adding break at the end of a normal case is unnecessary.
package main
import "fmt"
func main() {
number := 2
switch number {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
case 3:
fmt.Println("Three")
}
}
Output
Two
Only the matching case is executed. The next case does not run automatically.
Go Switch Fallthrough Behavior
The fallthrough keyword explicitly transfers control to the statements in the next case. Go does not test the next case’s expression before running it.
package main
import "fmt"
func main() {
number := 1
switch number {
case 1:
fmt.Println("One")
fallthrough
case 2:
fmt.Println("Two")
default:
fmt.Println("Other")
}
}
Output
One
Two
Use fallthrough only when unconditional execution of the next case is intended. For most grouped conditions, listing multiple values in one case is clearer.
Return a Value from a Go Switch Case
A switch statement does not itself produce a value, but a function can return directly from its cases.
package main
import "fmt"
func category(score int) string {
switch {
case score >= 90:
return "Excellent"
case score >= 75:
return "Good"
case score >= 50:
return "Pass"
default:
return "Fail"
}
}
func main() {
fmt.Println(category(82))
}
Output
Good
The cases are checked in order, so broader conditions should normally appear after more specific conditions.
Go Type Switch for Interface Values
A type switch selects a case according to the dynamic type stored in an interface value. It uses the form value.(type) and is valid only inside a type switch.
package main
import "fmt"
func describe(value any) {
switch v := value.(type) {
case int:
fmt.Println("Integer:", v)
case string:
fmt.Println("String:", v)
case bool:
fmt.Println("Boolean:", v)
default:
fmt.Printf("Unsupported type: %T\n", v)
}
}
func main() {
describe("Go")
describe(25)
}
Output
String: Go
Integer: 25
Inside each case, v has the type named by that case. A type switch can also include a nil case when the interface value itself may be nil.
Go Select Statement for Channel Operations
A normal switch chooses between values or conditions. Concurrent Go programs use the separate select statement to choose between channel send and receive operations. A channel operation should not be placed in a normal switch when the program needs to wait for whichever channel becomes ready first.
package main
import "fmt"
func main() {
messages := make(chan string, 1)
messages <- "ready"
select {
case message := <-messages:
fmt.Println(message)
default:
fmt.Println("No message available")
}
}
Output
ready
Rules for Writing Go Switch Cases
- Cases are evaluated from top to bottom.
- Only the first matching case runs unless it uses
fallthrough. - The
defaultcase is optional and may appear anywhere in the switch. - Case expressions must be valid for comparison with the switch expression.
- Multiple values can be grouped in one case using commas.
- A switch without an expression evaluates Boolean case conditions.
- An explicit
breakis usually unnecessary because Go exits the switch automatically.
Common Mistakes with Go Switch Statements
- Adding
breakto every case out of habit, even though Go breaks automatically. - Using
fallthroughto group cases instead of listing multiple values in one case. - Expecting a case after
fallthroughto have its condition checked. - Placing a broad Boolean condition before a more specific condition in an expressionless switch.
- Expecting string cases to match without regard to uppercase and lowercase letters.
- Using a normal switch when a
selectstatement is required for competing channel operations.
Frequently Asked Questions about Go Switch
How do you write a switch case in Go?
Write the switch keyword followed by an optional expression, then add one or more case blocks inside braces. An optional default block handles values that do not match any case.
Does a Go switch statement require break?
No. Go exits the switch automatically after the matching case finishes. A break statement is needed only for special control-flow situations, such as leaving an enclosing loop when used with a label.
How do you use multiple values in one Go switch case?
Separate the values with commas, as in case "Saturday", "Sunday":. The case executes when any listed value matches the switch expression.
What does fallthrough do in a Go switch?
fallthrough causes execution to continue into the next case’s statements without testing that next case’s condition. It should be used deliberately because it changes Go’s normal one-case-only behavior.
What is the difference between switch and select in Go?
switch chooses between values, conditions, or types. select chooses between channel communication operations and is used in concurrent Go programs.
Editorial QA Checklist for Go Switch Examples
- Confirm that each example executes only the stated matching case unless
fallthroughis present. - Verify that grouped case values use comma-separated values rather than duplicated case bodies.
- Check that expressionless switch cases are Boolean expressions ordered from most specific to least specific.
- Confirm that type-switch examples use an interface value and the exact
value.(type)syntax. - Verify that channel-choice examples use
selectrather than describing them as ordinary switch cases.
Summary of Go Switch Statements
In this Go Tutorial, we learned how to use expression switches, expressionless switches, multiple values in one case, short initialization statements, string cases, explicit fallthrough, direct returns, and type switches. Go executes the first matching case and normally exits the switch without requiring break.
TutorialKart.com