Learnmonkey Learnmonkey Logo

Go Switch

What is a Switch Statements?

You can use a switch statement when you have lots of if and else if statements in your code. For example:


if x == 1 {
    // do something
} else if x == 2 {
    // do something
} else if x == 3 {
    // do something
} else if x == 4 {
    // do something
}
// ... you get the idea
    

Instead, of this complicated, nasty code, we could have used a switch statement to save us lots of nasty code.

Switch statements work by having different cases for what a variable might be. That way, we can put our conditional code in the cases.

Implementing the Switch Statement

Below is an example of what we could do to replace the earlier nasty code:


switch x {
    case 1:
        // case where x is 1
    case 2:
        // case where x is 2
    case 3:
        // case where x is 3
    case 4:
        // case where x is 4
    // ... you get the idea
}
    

The very first line of our code is switch x {, which tells Go that we are making a switch using the variable x. All of our cases will go inside the curly brackets.

Then, we simply define all the cases using the syntax case [value]: and then write the code for the case below it.