A case statement selects one execution branch by comparing a switch expression with case conditions. Go uses implicit breaking, so execution does not continue into later cases. section 2.2.1
Use case statements to make multiple-condition logic explicit:
- Use a switch for several alternatives instead of a long if/else if/else chain. section 2.6 section 5.6
- Add a default branch for inputs that match no listed case. section 2.2.1 section 7.4.2
- Expect only the first eligible case to execute; use fallthrough only when entering another case is intentional. section 7.4.2 section 7.6
- Use select cases with channels when the code must respond to whichever channel operation becomes ready. section 9.7
Choosing a greeting
A typed language value keeps the function interface explicit, while the switch maps language codes to greetings: case "en" returns "Hello world", case "fr" returns "Bonjour le monde", and default returns an empty string. section 2.2.1
Updating a bounded cache
An upsert switch first removes an existing key, otherwise removes the oldest key when the cache is full, then inserts the new value. The test verifies that updating key 1 protects it while key 2 is discarded. section 7.4.2
Listing 2.6 main.go: Adding a new language
package main
import "fmt"
func main() {
greeting := greet("en")
fmt.Println(greeting)
}
// language represents the language's code
type language string #1
// greet says hello to the world in the specified language
func greet(l language) string {
switch l { #2
case "en":
return "Hello world"
case "fr":
return "Bonjour le monde"
default:
return ""
}
}
Inspect the complete Go program showing a custom language type, a greet function, switch cases, default handling, and the calling code. section 2.2.1








