Video Coming Soon...

Created by Zed A. Shaw Updated 2025-10-07 14:32:54

10: Flow Control: switch

WARNING This exercise is in DRAFT status, so there may be errors. If you find any, please email me at help@learncodethehardway.com so I can fix them.

A switch statement is similar to an if but it simplifies testing multiple variants of a variable. If you would write this:

x = 10
if x == 1 {
    // do something
} else if x == 2 {
    // do something
} else {
    // something else
}

Then a switch is better. You would rewrite the above like this:

x = 10
switch x {
    case 1:
        // do something
    case 2:
        // do something
    default:
        // something else
}

This makes it easier to see all the possible branches by their case, know that there's a default, and reduces the amount you have to type. You can also use a switch like a "super if":

j = 10
swith {
    case j == 1:
        // it's 1
    case j == 2:
        // it's 2
}

One important thing to remember about switch is that its case statements do not have fallthrough. In other languages you have to add a break to prevent the switch from running the next case like this:

// this is c code!
swith(x) {
    case 10:
        printf("10");
        break
    case 20:
        printf("20");
        break
    default:
        println("something else");
}

If you remove that first break then a language like C (or any others) would print out "10 20". Go made the right decision and breaks by default so you don't have to constantly remember this. If you do want this fallthrough behavior then there's the fallthrough keyword. Just place it after any block you want to...fallthrough.

The Code

Here's code that demonstrates the switch.

View Source file ex10/main.go Only

package main

import (
    "fmt"
)

func main() {
    fruit := "Apple"

    switch fruit {
    case "Apple":
        fmt.Println("You have Apples.")
    case "Orange":
        fmt.Println("You have Oranges.")
    case "Grape":
        fmt.Println("You have Grapes.")
    case "Durian":
        fmt.Println("You have Durian.")
    default:
        fmt.Println("You have some fruit.")
    }

    // you can also use a switch like a "super if"
    i := 23

    switch {
    case i < 20:
        fmt.Println("I is less than 20")
    case i > 20:
        fmt.Println("I is greater than 20")
    default:
        fmt.Println("Then what is i now?")
    }

}

The Breakdown

I'm going to assume you know that a } ends a block started by { and will only describe the other lines. I'm also going to skip the print lines since I've described those enough.

Make sure you understand every line of this code before continuing.

The Practice

As usual we'll do the three things that'll make you a better programmer:

  1. Break It -- You need to learn what error messages mean and what causes them, so break this code on purpose in as many ways as possible.
  2. Change It -- Try to craft as many different loops as possible. Take this as a game and try to make the most horrendous contraption imaginable. Can you throw some goto in the middle of a loop with an if that goes to random places?
  3. Remake It -- Write up a description of the code, hide or delete this, then try to recreate it using the process from Exercise 04: How to Write Code. Try to do this from memory as much as possible.

Study Drills

  1. Write a switch that uses fallthrough on purpose so you know how it works.
  2. Put an if inside one of the case block to see how that works.
  3. Put the switch inside a for loop.
  4. What happens if you put a goto in one of the case blocks?
Previous Lesson Next Lesson

Register for Learn Go the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.