Go switch programs choose one path out of many, which makes them perfect for menus, calculators and day names. In this post, you will build a working calculator and thirteen more switch programs, each with its exact output. Then you will practice the switch questions that test Go’s special rules, such as automatic break and fallthrough.
This post closes Level 2 of our Go programs series. It builds on Go if else programs, so read that first. For the theory of switch, see Go conditional statements explained. We tested every program on Go 1.27.
What are Go Switch Programs?
Go switch programs compare one value against a list of cases and run the first case that matches. If nothing matches, the optional default case runs.
Think of a lift in a building. You press a floor number, and the lift goes straight to that floor. It does not stop at every floor on the way to check. A switch works the same way, jumping straight to the matching case.
Why Go Switch Programs Matter
Long chains of if else that check one variable are hard to read. A switch makes the same logic short and clear. For example, a menu with six options, a calculator with four operators or a status code with many meanings all fit a switch well.
- Menus: pick an action from a numbered list.
- Calculators: run the right operation for
+,-,*or/. - Mapping values: turn a day number into a name, or a code into a message.
- Interviews: questions about
fallthroughand break rules are common.
How Go Switch Programs Work
Go checks the cases from top to bottom. It runs the first case that matches and then leaves the switch. Unlike C or Java, you do not need break, because Go stops after one case by itself.

The table below shows the kinds of switch you will use in Go switch programs.
| Kind | Example | Use it for |
|---|---|---|
| Value switch | switch day { case 1: } | Fixed values |
| Many values per case | case “Sat”, “Sun”: | Grouping matches |
| No condition | switch { case x > 90: } | Ranges, cleaner than if else |
| With init | switch d := today(); d { } | Keep a variable local |
| Type switch | switch v := x.(type) { } | Checking a value’s type |
Basic Go Switch Programs
These Go switch programs show the main forms of switch. We begin with the smallest possible example, so you can see the parts clearly.
Program 1: Traffic Light, the Easiest of the Go Switch Programs
This program looks at one colour and prints what a driver should do.
package main
import "fmt"
func main() {
light := "yellow" // := creates a new variable and sets its value
// switch compares light with each case, from top to bottom.
switch light {
case "red":
fmt.Println("Stop")
case "yellow":
fmt.Println("Slow down")
case "green":
fmt.Println("Go")
default: // runs only when no case matches
fmt.Println("Unknown colour")
}
}
Slow down
Go compares light with "red" first, and that does not match. Next it tries "yellow", which matches, so it prints “Slow down”. Then Go leaves the switch at once, so the "green" case never runs.
Program 2: Day Name from a Number
Now we put the switch inside a function, so we can call it for many numbers.
package main
import "fmt"
// dayName turns a number from 1 to 7 into the name of a weekday.
func dayName(dayNumber int) string {
switch dayNumber {
case 1:
return "Monday"
case 2:
return "Tuesday"
case 3:
return "Wednesday"
case 4:
return "Thursday"
case 5:
return "Friday"
case 6:
return "Saturday"
case 7:
return "Sunday"
default:
return "Invalid day"
}
}
func main() {
dayNumbers := []int{1, 5, 7, 9} // a slice (list) of numbers to test
// range gives each item; _ ignores the position we do not need.
for _, dayNumber := range dayNumbers {
fmt.Println(dayNumber, dayName(dayNumber))
}
}
1 Monday
5 Friday
7 Sunday
9 Invalid day
Each case returns a name, and default catches anything outside 1 to 7. The loop calls dayName once for every number in the slice. No break is needed anywhere.
Program 3: Weekday or Weekend
One case can list many values, separated by commas.
package main
import "fmt"
func main() {
days := []string{"Mon", "Sat", "Wed", "Sun"}
for _, day := range days {
switch day {
case "Sat", "Sun": // matches if day is "Sat" OR "Sun"
fmt.Println(day, "is a weekend")
case "Mon", "Tue", "Wed", "Thu", "Fri":
fmt.Println(day, "is a weekday")
}
}
}
Mon is a weekday
Sat is a weekend
Wed is a weekday
Sun is a weekend
The first case matches when the day is either “Sat” or “Sun”. The second case covers the five working days. So you need only two cases instead of seven.
Program 4: Vowel Check with a Rune Switch
package main
import "fmt"
func main() {
word := "Golang"
// range over a string gives one letter (a rune) at a time.
for _, letter := range word {
switch letter {
case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
fmt.Printf("%c vowel\n", letter) // %c prints a rune as a letter
default:
fmt.Printf("%c consonant\n", letter)
}
}
}
G consonant
o vowel
l consonant
a vowel
n consonant
g consonant
The loop hands each letter of “Golang” to the switch. If the letter is in the vowel list, the first case runs. Every other letter falls into default and prints “consonant”.
Program 5: Grade with a Switch Without a Condition
A switch with no value works like a clean if else chain. Each case holds its own condition.
package main
import "fmt"
func main() {
allMarks := []int{95, 81, 64, 40}
for _, marks := range allMarks {
// No value after switch, so each case is a true or false check.
switch {
case marks >= 90:
fmt.Println(marks, "A")
case marks >= 75:
fmt.Println(marks, "B")
case marks >= 50:
fmt.Println(marks, "C")
default:
fmt.Println(marks, "Fail")
}
}
}
95 A
81 B
64 C
40 Fail
Go runs the first case whose condition is true. For 81, the first check fails, but marks >= 75 passes. Order still matters, just as in our if else grade program.
Program 6: Even or Odd with a Switch
This short program uses the remainder of a division to pick a case.
package main
import "fmt"
func main() {
numbers := []int{4, 7, 10}
for _, number := range numbers {
// % gives the remainder. An even number has remainder 0 when divided by 2.
switch number % 2 {
case 0:
fmt.Println(number, "is even")
default:
fmt.Println(number, "is odd")
}
}
}
4 is even
7 is odd
10 is even
The switch checks number % 2, which is always 0 or 1. When it is 0, the number is even. Otherwise the default case says the number is odd.
A Calculator Program with Go Switch
The calculator is the most famous of all Go switch programs. We switch on the operator and handle division by zero.
Program 7: Simple Calculator
package main
import "fmt"
// calculate applies the operator to two numbers and returns the result or an error.
func calculate(first float64, operator string, second float64) (float64, error) {
switch operator {
case "+":
return first + second, nil // nil means "no error"
case "-":
return first - second, nil
case "*", "x":
return first * second, nil
case "/":
if second == 0 {
return 0, fmt.Errorf("cannot divide by zero") // Errorf makes a new error
}
return first / second, nil
default:
return 0, fmt.Errorf("unknown operator %q", operator) // %q adds quotes
}
}
// problem holds one calculation to try.
type problem struct {
first float64
operator string
second float64
}
func main() {
problems := []problem{
{12, "+", 8}, {9, "-", 14}, {6, "x", 7},
{22, "/", 7}, {5, "/", 0}, {2, "%", 3},
}
for _, item := range problems {
result, err := calculate(item.first, item.operator, item.second) // err is the error value
if err != nil {
fmt.Printf("%g %s %g -> error: %v\n", item.first, item.operator, item.second, err)
continue // skip to the next problem
}
fmt.Printf("%g %s %g = %.2f\n", item.first, item.operator, item.second, result)
}
}
12 + 8 = 20.00
9 - 14 = -5.00
6 x 7 = 42.00
22 / 7 = 3.14
5 / 0 -> error: cannot divide by zero
2 % 3 -> error: unknown operator "%"
The function returns a result and an error, which is the normal Go style. If err is not nil, we print the error and move on. %g prints numbers without extra zeros, so 12 prints as 12, and %.2f shows two decimal places.
Program 8: Interactive Calculator with User Input
This version reads expressions like 8 * 5 until the user types q. It uses the input tools from our Go user input programs.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin) // reads the keyboard line by line
fmt.Println("Enter a op b (or q to quit)")
for scanner.Scan() { // Scan waits for the next line and returns false at the end
line := strings.TrimSpace(scanner.Text())
if line == "q" {
fmt.Println("Bye!")
break // leave the for loop
}
// Step 1: split the line into number, operator, number.
var first, second float64
var operator string
_, err := fmt.Sscan(line, &first, &operator, &second) // & lets Sscan fill our variables
if err != nil {
fmt.Println("Format: 8 * 5")
continue
}
// Step 2: do the maths for the chosen operator.
switch operator {
case "+":
fmt.Println("=", first+second)
case "-":
fmt.Println("=", first-second)
case "*":
fmt.Println("=", first*second)
case "/":
if second == 0 {
fmt.Println("Cannot divide by zero")
} else {
fmt.Println("=", first/second)
}
default:
fmt.Println("Unknown operator", operator)
}
}
}
We type these lines one by one.
8 * 5
10 / 4
7 ^ 2
hello
q
Enter a op b (or q to quit)
= 40
= 2.5
Unknown operator ^
Format: 8 * 5
Bye!
fmt.Sscan splits each line into a number, an operator and a number. If the line has the wrong shape, we print a hint and wait for the next line. When the user types q, break ends the loop and the program stops.
More Real-Life Go Switch Programs
These Go switch programs show the other switch features.
Program 9: Days in a Month
package main
import "fmt"
// isLeapYear reports whether February has 29 days in this year.
func isLeapYear(year int) bool {
if year%400 == 0 {
return true
}
if year%100 == 0 {
return false
}
return year%4 == 0
}
// daysIn returns how many days the month has in the given year.
func daysIn(month, year int) int {
switch month {
case 4, 6, 9, 11: // April, June, September, November
return 30
case 2: // February depends on the year
if isLeapYear(year) {
return 29
}
return 28
default:
return 31
}
}
func main() {
fmt.Println("Feb 2024:", daysIn(2, 2024))
fmt.Println("Feb 2026:", daysIn(2, 2026))
fmt.Println("Apr 2026:", daysIn(4, 2026))
fmt.Println("Dec 2026:", daysIn(12, 2026))
}
Feb 2024: 29
Feb 2026: 28
Apr 2026: 30
Dec 2026: 31
The four short months share one case and return 30. February calls isLeapYear to choose between 29 and 28. Every other month falls into default and gets 31 days.
Program 10: Switch with an Init Statement
Like if, a switch can run a short statement first. The variable stays inside the switch.
package main
import (
"fmt"
"strings"
)
func main() {
input := " Start "
// Before the ; we create command. After the ; we switch on it.
switch command := strings.ToLower(strings.TrimSpace(input)); command {
case "start":
fmt.Println("Starting the server")
case "stop":
fmt.Println("Stopping the server")
default:
fmt.Println("Unknown command:", command)
}
}
Starting the server
TrimSpace removes the extra spaces, and ToLower makes the text small letters. We clean the input inside the init statement, so ” Start ” still matches “start”. You cannot use command after the switch ends.
Program 11: fallthrough to the Next Case
fallthrough forces Go to also run the next case, without checking it. It is rare, but interviewers like to ask about it.
package main
import "fmt"
func main() {
level := 2
switch level {
case 1:
fmt.Println("Read access")
fallthrough // also run the next case
case 2:
fmt.Println("Write access")
fallthrough
case 3:
fmt.Println("Delete access")
case 4:
fmt.Println("Admin access")
}
}
Write access
Delete access
Level 2 matches case 2, then fallthrough runs case 3 too. Case 3 has no fallthrough, so Go stops there and never reaches case 4.
Program 12: Type Switch
A type switch checks the real type stored in an any value. This is useful when data can come in different forms.
package main
import "fmt"
// describe tells you what kind of value it was given.
// any means the input can hold a value of any type.
func describe(input any) string {
// value gets the matching type inside each case.
switch value := input.(type) {
case int:
return fmt.Sprintf("int with value %d", value)
case string:
return fmt.Sprintf("string of length %d", len(value))
case bool:
return fmt.Sprintf("bool %t", value)
case nil: // nil means "nothing inside"
return "nil value"
default:
return fmt.Sprintf("other type %T", value) // %T prints the type name
}
}
func main() {
fmt.Println(describe(42))
fmt.Println(describe("Golang"))
fmt.Println(describe(true))
fmt.Println(describe(nil))
fmt.Println(describe(3.5))
}
int with value 42
string of length 6
bool true
nil value
other type float64
input.(type) asks Go which type is stored inside. Inside each case, value already has the matching type, so len(value) works for the string. Our type assertion and type switch guide covers this in depth.
Program 13: HTTP Status Messages
package main
import "fmt"
func main() {
codes := []int{200, 201, 404, 500, 302}
for _, code := range codes {
switch {
case code >= 200 && code < 300: // && means "and"
fmt.Println(code, "Success")
case code >= 300 && code < 400:
fmt.Println(code, "Redirect")
case code >= 400 && code < 500:
fmt.Println(code, "Client error")
default:
fmt.Println(code, "Server error")
}
}
}
200 Success
201 Success
404 Client error
500 Server error
302 Redirect
Each case checks a range of codes with two conditions joined by &&. A code like 201 falls in the first range, so it is a success. Anything 500 or above reaches default.
Program 14: Season from a Month
package main
import "fmt"
func main() {
months := []string{"Jan", "Apr", "Jul", "Oct"}
for _, month := range months {
var season string // starts as an empty string
switch month {
case "Mar", "Apr", "May":
season = "Summer"
case "Jun", "Jul", "Aug", "Sep":
season = "Monsoon"
case "Oct", "Nov":
season = "Autumn"
default:
season = "Winter"
}
fmt.Println(month, season)
}
}
Jan Winter
Apr Summer
Jul Monsoon
Oct Autumn
The switch stores a name in season, and we print it after the switch. Months not listed, such as “Jan”, get “Winter” from default. These are the Indian seasons, which is why monsoon gets four months.
Go Switch Programs vs if else
Both tools make decisions, so here is when Go switch programs are the better choice and when if else wins.

| Feature | switch | if else |
|---|---|---|
| Best for | One value, many matches | Few mixed conditions |
| Needs break | No, automatic | Not used |
| Many values in one branch | Yes, case 1, 2, 3 | Needs or between checks |
| Type checks | Type switch | Type assertion with ok |
| Readability with 5+ branches | High | Low |
In short, reach for switch when you compare one value against many options. Use if else for two or three unrelated conditions.
Common Mistakes in Go Switch Programs
- Adding break out of habit: it is not needed, and it can confuse readers.
- Thinking break leaves a loop: inside a switch,
breakonly leaves the switch. - Expecting fallthrough to check the next case: it runs the next case without any check.
- Duplicate cases: the same constant in two cases is a compile error.
- Missing default: without it, unknown values do nothing silently.
Best Practices for Go Switch Programs
- Always add a default case, even if it only logs an error.
- Group values with commas instead of repeating code.
- Use a switch with no condition for ranges, since it reads better than long if else chains.
- Avoid fallthrough unless the steps truly build on each other.
- Return from cases inside small functions, which keeps the code short.
Go Switch Programs Interview Questions and Answers
Interviewers use short Go switch programs to test the special rules of switch. Each program is complete, with real output from Go 1.27.
Rule Questions on Go Switch Programs
Q1. Do you need break in a Go switch?
No. Go leaves the switch after the first matching case. You use fallthrough when you want the next case to run too.
Q2. What does this program print?
package main
import "fmt"
func main() {
number := 1
switch number {
case 1:
fmt.Println("one")
fallthrough
case 5:
fmt.Println("five")
default:
fmt.Println("default")
}
}
one
five
fallthrough runs case 5 even though number is not 5. It does not continue into default, because case 5 has no fallthrough of its own.
Q3. Why does this program not compile?
package main
import "fmt"
func main() {
number := 2
switch number {
case 1:
fmt.Println("one")
case 1: // the same value again is not allowed
fmt.Println("uno")
}
}
duplicate case 1 (constant of type int) in expression switch
Go checks constant cases at compile time and rejects duplicates. This catches copy-paste mistakes early.
Q4. Where can default go in a switch?
Anywhere. Go always tries every other case first, and runs default only when none match. Still, putting it last is the normal style.
package main
import "fmt"
func main() {
switch 3 {
default: // written first, but checked last
fmt.Println("default")
case 3:
fmt.Println("three")
}
}
three
Even though default comes first, Go tries case 3 before it. That case matches, so “three” prints.
Q5. Can you use fallthrough in the last case?
package main
import "fmt"
func main() {
switch 1 {
case 1:
fmt.Println("one")
fallthrough // there is no next case to fall into
}
}
cannot fallthrough final case in switch
No. There is no next case to fall into, so the program does not compile. You also cannot use fallthrough in a type switch.
Output Questions
Q6. What does this program print?
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
switch i {
case 2:
break // leaves only the switch, not the loop
default:
fmt.Print(i, " ")
}
}
fmt.Println("done")
}
1 3 done
break only leaves the switch for i = 2. The loop keeps going, so 3 is printed after it.
Q7. What does this program print?
package main
import "fmt"
// check prints the number and gives it back, so we can see when it runs.
func check(number int) int {
fmt.Println("checking", number)
return number
}
func main() {
switch 2 {
case check(1), check(2), check(3):
fmt.Println("matched")
}
}
checking 1
checking 2
matched
Go checks case values from left to right and stops at the first match. So check(3) never runs.
Q8. What does this program print?
package main
import "fmt"
func main() {
// number is created before the ; and there is no value after it.
switch number := 5; {
case number > 3:
fmt.Println("big")
fallthrough
case number > 10:
fmt.Println("huge")
}
}
big
huge
The second case is false, but fallthrough runs it anyway. That is why “huge” prints even though 5 is not above 10.
Q9. What does this program print?
package main
import "fmt"
func main() {
var value any = 10 // an int stored in an any
switch value.(type) {
case string:
fmt.Println("string")
case int, int64:
fmt.Println("some int")
}
var empty any // holds nothing yet, so it is nil
switch empty.(type) {
case nil:
fmt.Println("nil")
}
}
some int
nil
A type case can list many types. An interface with nothing inside matches case nil.
Q10. What does this program print?
package main
import "fmt"
func main() {
grade := 'B' // a rune, written with single quotes
switch grade {
case 'A':
fmt.Println("Excellent")
case 'B', 'C':
fmt.Println("Well done")
case 'D':
fmt.Println("Passed")
default:
fmt.Println("Invalid")
}
}
Well done
The grade 'B' is in the list of the second case. So Go prints “Well done” and leaves the switch.
Q11. Why does this program not compile?
package main
import "fmt"
func main() {
number := 5
switch number {
case "5": // a string, but number is an int
fmt.Println("five")
}
}
cannot convert "5" (untyped string constant) to type int
Every case must match the type of the switch value. Here number is an int, and Go cannot turn the string “5” into an int, so the case is an error.
Q12. Can a switch case use a function call or variable?
Yes. Unlike C, Go cases can be any expression, not only constants. Go evaluates them at run time from top to bottom.
Q13. When should you choose switch over a map lookup?
Use a map when you only turn one value into another, such as a code into a message. Use a switch when each case runs different logic, such as the steps in a calculator.
Q14. What does this program print?
package main
import "fmt"
func main() {
switch {
case false:
fmt.Println("A")
case true:
fmt.Println("B")
case true:
fmt.Println("C")
}
}
B
A switch without a value compares each case with true. The second case is the first true one, so only “B” prints.
Practice Task
Menus are the most practical Go switch programs. Build one that shows four options: 1 Add item, 2 Remove item, 3 Show items and 4 Exit. Read the choice in a loop and use a switch to handle each option. Hint: keep the items in a slice of strings and use break with a label to leave the loop on option 4.
Official Resources
Quick Recap
- Go switch programs run the first matching case and leave automatically, with no break needed.
- One case can list many values, and a switch without a value works like an if else chain.
fallthroughruns the next case without checking it.- A type switch checks the real type inside an
anyvalue. - Always add a
defaultcase so unknown values are handled.
What’s Next?
That completes Level 2 of our Go programs series. Coming soon: Level 3, starting with Go string programs such as reverse a string, palindrome and character count. Until then, revise with the Go control flow interview questions.


