Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
golang
switch

Switch statement in Golang

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring