Go > Core Go Basics > Control Flow > Switch statements
Go Switch Statement - Basic Example
This snippet demonstrates the fundamental usage of a switch statement in Go. It shows how to evaluate a variable against different cases and execute the corresponding code block. This is the simplest form of a switch, similar to other languages.
Basic Switch Statement Structure
This code defines a variable fruit and uses a switch statement to check its value. Each case compares the value of fruit against a specific string. If a match is found, the corresponding fmt.Println statement is executed. The default case is executed if none of the other cases match.
package main
import "fmt"
func main() {
fruit := "apple"
switch fruit {
case "banana":
fmt.Println("It's a banana!")
case "apple":
fmt.Println("It's an apple!")
case "orange":
fmt.Println("It's an orange!")
default:
fmt.Println("Unknown fruit.")
}
}
Concepts Behind the Snippet
The switch statement provides a clean and efficient way to handle multiple conditional checks based on the value of a single expression. It evaluates the expression once and then compares the result to a series of possible values defined in the case clauses. The default clause acts as a catch-all if no other cases match. Go's switch statement is more powerful than in some other languages (like C or Java) because it doesn't require a break statement at the end of each case. Execution automatically exits the switch after a matching case is executed.
Real-Life Use Case
Switch statements are useful in scenarios where you need to perform different actions based on the value of a variable. For instance, you could use a switch statement to handle different HTTP request methods (GET, POST, PUT, DELETE), process different types of messages received from a queue, or implement a state machine.
Best Practices
default case to handle unexpected or invalid values. This prevents unexpected behavior and makes your code more robust.case statements for better readability and maintainability.case, you don't need to enclose them in a block ({}) unless you're declaring new variables within that scope.
When to Use Them
Use switch statements when you have a single expression or variable that needs to be compared against multiple possible values. If you have complex conditional logic involving multiple variables and conditions, an if-else-if chain might be more appropriate. However, if the logic depends on a single value with multiple potential outcomes, a switch is generally more readable.
Memory footprint
The memory footprint of a switch statement itself is minimal. It primarily depends on the size of the variable being evaluated and the complexity of the code executed within each case. The switch statement itself doesn't allocate significant memory.
alternatives
The main alternative to a switch statement is a chain of if-else if-else statements. For very simple conditions, a direct if-else might suffice. For more complex scenarios involving multiple variables and logical operators, if-else if-else chains are often necessary. However, for simple comparisons of a single value, switch statements often enhance readability.
pros
cons
FAQ
-
Does Go require a 'break' statement in each case?
No, Go doesn't require abreakstatement at the end of eachcase. Execution automatically exits theswitchafter a matchingcaseis executed. To explicitly fall through to the next case, use thefallthroughkeyword. -
Can I use different data types in the case values?
No, all case values in aswitchstatement must be of the same data type as the expression being evaluated. Mixing types will result in a compile-time error.