Switch statement in Golang
A switch statement is a shorter way to write a sequence of if-else statements. switch runs the first case whose value is equal to the condition expression.
How it works
switch is passed a variable whose value is compared to each case value. If there is a match, the corresponding block of code is executed.
Syntax
switch optstatement; optexpression{
case expression1: Statement..
case expression2: Statement..
...
default: Statement..
}
- Both
optstatementandoptexpressionin the expression switch are optional statements. - If both
optstatementandoptexpressionare present, then a semi-colon(;) is required in-between them. - Each of the
caseexpressions compares the switch variable’s value with the expression value. If the values match, the statements inside that particular switch are executed.
Code
The following code demonstrates a simple switch-case example:
Go’s switch is like the one in C, C++, Java, JavaScript, and PHP, except that Go only runs the selected case, not all the cases that follow.
package mainimport ("fmt")func main() {i := 2fmt.Print("Write ", i, " as ")switch i {case 1:fmt.Println("one")case 2:fmt.Println("two")case 3:fmt.Println("three")}}
Switch without an expression
The code below shows how switch without an expression is an alternate way to express if/else logic. The code also shows how the case expressions can be non-constant.
package mainimport ("fmt""time")func main() {t := time.Now()fmt.Println(t)switch {case t.Hour() < 12:fmt.Println("It's before noon")default:fmt.Println("It's after noon")}}
Switch with both an expression and a statement
package mainimport "fmt"func main() {switch i:=2; i{case 1:fmt.Println("one")case 2:fmt.Println("two")case 3:fmt.Println("three")}}
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved