Switch-Case Branch Statements

GoGoBeginner
Practice Now

Introduction

In the previous experiment, we learned about the usage of if branch statements. In this lab, we will learn about switch-case branch statements. Compared to if statements, switch statements are more suitable for multiple condition scenarios.

Knowledge Points:

  • switch-case statements
  • default keyword
  • fallthrough keyword

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go/FunctionsandControlFlowGroup -.-> go/switch("`Switch`") go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") subgraph Lab Skills go/switch -.-> lab-149072{{"`Switch-Case Branch Statements`"}} go/functions -.-> lab-149072{{"`Switch-Case Branch Statements`"}} end

Basic Syntax

The syntax of the switch branch statement is similar to that of the if branch statement, as they both have conditional judgments. The basic syntax is as follows:

switch condition {
    case val1:
        // code block
    case val2:
        // code block
    ...
    default:
        // code block
}

The condition can be any type of variable. When the condition matches the value of a certain case statement, the corresponding case statement will be executed, and after the execution, it will exit the current switch branch.

The variable value in the case statement needs to be of the same type.

The program will match from top to bottom in the case statement and execute the code of the branch that matches the condition. After the execution is complete, it will exit the current switch branch.

The default statement is similar to the else statement. When other case statements do not match the condition, the default statement will be executed.

Let's take a look at an example of a weather forecast. Create a new file named switch.go and write the following code:

package main

import (
    "fmt"
)

func main() {
    // Today's weather
    weather := "rainy"
    switch weather {
    case "snow":
        fmt.Println("Remember to wear a scarf today.🧣")
    case "rainy":
        fmt.Println("Remember to bring an umbrella today.🌂")
    default:
        fmt.Println("Today is sunny.☀")
    }
}

After running the code, the output is as follows:

Remember to bring an umbrella today.🌂

This weather forecast will output different results based on different weather conditions. First, we set today's weather as "rainy". In the switch-case branch below, we set three different conditions. When it snows, we remind you to wear a scarf, when it rains, we remind you to bring an umbrella, and otherwise, we consider it as a sunny day.

Multiple Values in a Branch

The case statement can also have multiple values, as shown below:

switch condition {
    case val1, val2:
        // code block
    ...
}

We have updated the weather program as follows:

package main

import (
    "fmt"
)

func main() {
    // Today's weather
    weather := "snow"
    switch weather {
    case "snow", "stormy":
        fmt.Println("Remember to wear a scarf today.🧣")
    case "haze", "sandstorm":
        fmt.Println("Remember to wear a mask today.😷")
    case "rainy":
        fmt.Println("Remember to bring an umbrella today.🌂")
    default:
        fmt.Println("Today is sunny.☀")
    }
}

After running the code, the output is as follows:

Remember to wear a scarf today.🧣

We added some weather conditions. We need to wear a mask when it is hazy or a sandstorm.

switch Statements with No Conditional Variable

The conditional variable in the switch statement is an optional parameter. When the conditional variable is empty, the switch statement will be similar to the if-else statement.

We have rewritten the program output today's day of the week in the previous section using the switch statement without a conditional variable:

package main

import (
    "fmt"
    "time"
)

func main() {
    today := time.Now().Weekday()
    switch {
    case today == time.Monday:
        fmt.Println("Today is Monday.")
    case today == time.Tuesday:
        fmt.Println("Today is Tuesday.")
    case today == time.Wednesday:
        fmt.Println("Today is Wednesday.")
    case today == time.Thursday:
        fmt.Println("Today is Thursday.")
    case today == time.Friday:
        fmt.Println("Today is Friday.")
    case today == time.Saturday:
        fmt.Println("Today is Saturday.")
    default:
        fmt.Println("Today is Sunday.")
    }
}

After running the code, the output is as follows:

Today is Monday.

In this program, we removed the conditional variable in the switch statement. When the program is running, it will check whether the conditions in each case branch are met. When a case condition is met, the code in that branch will be executed, and finally, it will exit the switch branch.

fallthrough Statement

As mentioned earlier, after a program executes a case branch, it will exit the current switch branch.

If you want to continue executing the next branch statement after executing a case branch, you can use the fallthrough statement.

Here are the specifications for using the fallthrough statement:

  • By default, after the switch statement matches and executes case 10, it will not continue to execute the subsequent branches. The fallthrough statement will execute the subsequent case branches.
  • fallthrough only affects the next case statement and does not perform case checking.
  • fallthrough cannot be used in the last branch of switch.

Let's see a specific example:

package main

import (
    "fmt"
)

func main() {
    n := 10
    switch n {
    case 10:
        fmt.Println(1)
        fallthrough
    case 3:
        fmt.Println(3)
    }
}

After running the code, the output is as follows:

10
3

The switch branch outputs after the case 10 statement is matched, and then it outputs the next case statement of fallthrough.

Initialization Statement in switch

In Go, not only if branch statements have initialization statements, but switch branch statements also have them. We can write the initialization statement before the conditional variable, separated by a semicolon.

Quiz

Now we will rewrite the program from the previous section and move the initialization statement into the switch statement.

Create a new file named switch2.go. Write the following code into the switch2.go file. Modify the program from the previous section and move the initialization statement into the switch statement.

The code from the previous section is as follows:

package main

import (
    "fmt"
)

func main() {
    n := 10
    switch n {
    case 10:
        fmt.Println(1)
        fallthrough
    case 3:
        fmt.Println(3)
    }
}

Requirements:

  • The switch2.go file should be placed under the ~/project directory.

Hint: You can refer to the initialization program section in the if-else experiment for modifying.

Summary

In this lab, we explained the switch branch statement. The main points are as follows:

  • When the case statement matches and executes, it will exit the current switch branch.
  • You can use fallthrough to continue executing the next case statement.
  • switch also has an initialization statement, separated by a semicolon from the conditional variable.

In the next experiment, we will explain Go's loop statements.

Other Go Tutorials you may like