When you have many conditions to check against a single value, writing multiple if-else if statements can become messy. The switch statement provides a cleaner way to handle multiple conditions.
A switch statement evaluates an expression once and compares it against multiple possible values.
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of the work week")
case "Friday":
fmt.Println("Almost weekend!")
case "Saturday", "Sunday":
fmt.Println("Weekend!")
default:
fmt.Println("Midweek day")
}
// Output: Start of the work week
The switch statement evaluates the expression (in this case, day) and then checks each case in order. When it finds a matching case, it executes that block and then exits the switch - no break statement needed!
grade := "B"
switch grade {
case "A":
fmt.Println("Excellent!")
case "B":
fmt.Println("Good job!")
case "C":
fmt.Println("Passing")
case "D", "F":
fmt.Println("Needs improvement")
default:
fmt.Println("Invalid grade")
}
// Output: Good job!
Notice in the examples above that you can check multiple values in a single case by separating them with commas. This is cleaner than writing multiple cases or using logical OR operators.
month := "December"
switch month {
case "December", "January", "February":
fmt.Println("Winter")
case "March", "April", "May":
fmt.Println("Spring")
case "June", "July", "August":
fmt.Println("Summer")
case "September", "October", "November":
fmt.Println("Fall")
}
// Output: Winter
The default case is optional and executes when no other case matches. It's like the else in an if-else chain.
number := 7
switch number {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
default:
fmt.Println("Other number")
}
// Output: Other number
Compare these two approaches:
// Using if-else
if status == "active" {
fmt.Println("Running")
} else if status == "paused" {
fmt.Println("Paused")
} else if status == "stopped" {
fmt.Println("Stopped")
} else {
fmt.Println("Unknown")
}
// Using switch - much cleaner!
switch status {
case "active":
fmt.Println("Running")
case "paused"
For this challenge, create a function called printCharacterSpecies that accepts a name parameter (string) and uses a switch statement to print the species of different Dragon Ball characters.
Implement the following cases:
"Saiyan""Human""Namekian""Unknown"The function signature is:
func printCharacterSpecies(name string) {
// Your code here
}