Go — Choosing a branch with switch
A Go switch without a tag checks Boolean cases from top to bottom. The first matching case runs, and default handles a stock count outside the earlier cases.
A simple example
Match one case
- Start with Value 2
- Do this Match case 2
- Result two
package main
import "fmt"
func main() {
switch 2 {
case 2:
fmt.Println("two")
default:
fmt.Println("other")
}
}
two
Classify a stock level
A switch without a selector compares each case condition to true. Go finishes the selected case automatically. Place the exact zero test before the broader low-stock threshold.
A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.
Run the example
Go 1.20 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
)
func main() {
stock := 3
var status string
switch {
case stock == 0:
status = "sold out"
case stock <= 5:
status = "order soon"
default:
status = "in stock"
}
fmt.Println(status)
}
order soon
The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.
Try it yourself
Try the boundary values 0, 5, and 6.
Check your answer
They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.