- Author

- Name
- Nelson Silva
- Social
Introduction
The switch is a powerful tool in Go, allowing programmers to make decisions based on multiple cases. Unlike conditionals with if and else, switch is often more readable, especially when dealing with many conditions.
Switch Fundamentals
- Equality Check: The
switchcompares the given expression against the values of eachcase. - Single Execution: Unlike other languages, in Go, once a
casematches, the program exits theswitchblock. No explicit "break" is needed. - Default Clause: If no
casematches, the code underdefaultwill be executed. However,defaultis optional.
Basic Switch
day := "thursday"
switch day {
case "monday":
fmt.Println("Today is Monday.")
case "tuesday":
fmt.Println("Today is Tuesday.")
default:
fmt.Println("It is neither Monday nor Tuesday.")
}
Switch with Multiple Conditions in a Case
You can combine multiple possible values in a single case:
letter := 'B'
switch letter {
case 'A', 'E', 'I', 'O', 'U':
fmt.Println("Vowel")
default:
fmt.Println("Consonant")
}
Switch with Initializer
Just like the if statement, switch can also have an initialization:
switch num := 5; num {
case 1, 3, 5, 7, 9:
fmt.Println("Odd number")
default:
fmt.Println("Even number")
}
Type Switch
Go also supports a type-based switch, which is useful when working with interfaces:
var x interface{} = "text"
switch x.(type) {
case int:
fmt.Println("x is an integer")
case string:
fmt.Println("x is a string")
default:
fmt.Println("Unknown type")
}
Conclusion
The switch statement in Go offers a clean and efficient way to handle multiple conditions. Whether checking values or types, switch makes code more organized and readable.