In this tutorial, we will learn about the switch statement in Go. We will cover the basics of using the switch statement, including how to handle multiple cases, use fallthrough, and switch on different types.
A switch statement in Go is used to execute one block of code among many options. It is an alternative to using multiple if
statements.
The basic syntax of a switch statement in Go is:
switch expression {
case value1:
// statements
case value2:
// statements
default:
// default statements
}
Go allows multiple cases to be combined into a single case using commas.
switch expression {
case value1, value2:
// statements
}
The fallthrough
statement can be used to continue execution to the next case.
switch expression {
case value1:
// statements
fallthrough
case value2:
// statements
}
A type switch is used to compare types instead of values.
switch x.(type) {
case type1:
// statements
case type2:
// statements
}
We can use a basic switch statement in Go to execute one block of code among multiple options.
For example,
day
and assign it a 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("Invalid day")
}
}
Wednesday
We can use a switch statement with multiple cases combined into a single case.
For example,
day
and assign it a value.package main
import "fmt"
func main() {
day := 6
switch day {
case 1, 2, 3, 4, 5:
fmt.Println("Weekday")
case 6, 7:
fmt.Println("Weekend")
default:
fmt.Println("Invalid day")
}
}
Weekend
We can use the fallthrough statement in a switch case to continue execution to the next case.
For example,
grade
and assign it a value.package main
import "fmt"
func main() {
grade := "B"
switch grade {
case "A":
fmt.Println("Excellent")
fallthrough
case "B":
fmt.Println("Good")
fallthrough
case "C":
fmt.Println("Average")
default:
fmt.Println("Invalid grade")
}
}
Good Average
We can use a type switch to compare types instead of values in Go.
For example,
i
and assign it a value of any type.package main
import "fmt"
func main() {
var i interface{} = 42
switch v := i.(type) {
case int:
fmt.Printf("%T is an int\n", v)
case float64:
fmt.Printf("%T is a float64\n", v)
case string:
fmt.Printf("%T is a string\n", v)
default:
fmt.Printf("%T is an unknown type\n", v)
}
}
int is an int