Introduction
The switch statement in Go provides a concise way to select one of many code blocks to be executed based on the value of an expression. It is similar to switch statements in other programming languages like C, C++, Java, JavaScript, and PHP, but with some unique features. Let's dive into how the switch statement works in Go with examples and output.
Basic Syntax and Functionality
The basic syntax of the switch statement in Go is as follows:
switch expression {
case value1:
// code block
case value2:
// code block
...
default:
// code block
}
Here's how it works:
The expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The
default
keyword is optional and specifies code to run if there is no case match.
Single-Case Switch Example
Let's start with a simple example where we use a weekday number to calculate the weekday name:
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")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
}
}
Output:
Wednesday
Using the default
Keyword
The default
keyword is useful for handling cases where none of the defined cases match the expression value. Here's an example:
package main
import "fmt"
func main() {
day := 8
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("Invalid day")
}
}
Output:
Invalid day
Type Matching in Case Values
All the case values should have the same type as the switch expression. Otherwise, the compiler will raise an error. Let's see an example of this:
package main
import "fmt"
func main() {
a := 5
switch a {
case 1:
fmt.Println("a is one")
case "b":
fmt.Println("a is b")
}
}
Output:
./prog.go:11:2: cannot use "b" (type untyped string) as type int
Conclusion
The switch statement in Go provides a clean and efficient way to handle multiple conditions based on the value of an expression. By understanding its syntax and behavior, you can leverage its power to write more structured and readable code in your Go programs. Experiment with switch statements in your own projects to become proficient in their usage.