Switch Case Basics
Introduction to Switch Statements
In Golang, the switch
statement provides a powerful way to perform conditional branching. Unlike traditional if-else
statements, switch cases offer a more readable and concise method for handling multiple conditions.
Basic Syntax
A basic switch statement in Go follows this structure:
switch expression {
case value1:
// Code to execute when expression matches value1
case value2:
// Code to execute when expression matches value2
default:
// Code to execute when no other cases match
}
Simple Example
Here's a simple example demonstrating a basic switch statement:
package main
import "fmt"
func main() {
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of the work week")
case "Friday":
fmt.Println("End of the work week")
case "Saturday", "Sunday":
fmt.Println("Weekend!")
default:
fmt.Println("Midweek day")
}
}
Key Characteristics
Feature |
Description |
Automatic Break |
Go switch cases automatically break after matching |
Multiple Values |
A single case can match multiple values |
Fallthrough Keyword |
Use fallthrough to continue to next case |
Switch Without Expression
Go also supports a switch statement without an initial expression:
switch {
case x > 0:
fmt.Println("Positive")
case x < 0:
fmt.Println("Negative")
default:
fmt.Println("Zero")
}
Type Switch
Go provides a special type of switch for type checking:
func checkType(x interface{}) {
switch x.(type) {
case int:
fmt.Println("Integer")
case string:
fmt.Println("String")
case bool:
fmt.Println("Boolean")
default:
fmt.Println("Unknown type")
}
}
Flow Diagram
graph TD
A[Start Switch] --> B{Evaluate Expression}
B --> |Match Case 1| C[Execute Case 1]
B --> |Match Case 2| D[Execute Case 2]
B --> |No Match| E[Execute Default]
C --> F[End]
D --> F
E --> F
By understanding these basics, you'll be well-equipped to use switch statements effectively in your Golang programs. LabEx recommends practicing these patterns to improve your switch statement skills.