Trusted answers to developer questions

Switch statement in Golang

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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.

svg viewer

Syntax

switch optstatement; optexpression{
case expression1: Statement..
case expression2: Statement..
...
default: Statement..
}
  • Both optstatement and optexpression in the expression switch are optional statements.
  • If both optstatement and optexpression are present, then a semi-colon(;) is required in-between them.
  • Each of the case expressions 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 main
import (
"fmt"
)
func main() {
i := 2
fmt.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 main
import (
"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 main
import "fmt"
func main() {
switch i:=2; i{
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
}

RELATED TAGS

go
golang
switch
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?