Lesson contents

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

  1. Start with Value 2
  2. Do this Match case 2
  3. Result two
The matching case supplies the word. A different value can take the default path.
main.go
package main

import "fmt"


func main() {
    switch 2 {
    case 2:
        fmt.Println("two")
    default:
        fmt.Println("other")
    }
}
Output
two
Advertisements

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.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

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
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)
}
Output
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.

A Tour of Go

Related tags

  • Go
  • conditions
  • branching
  • comparison