Switch-Case Branch Statements in Golang

GolangGolangBeginner
Practice Now

Introduction

In the previous lab, we learned about the usage of if-else branch statements. In this lab, we will learn about switch-case branch statements. Compared to if-else 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(("`Golang`")) -.-> go/BasicsGroup(["`Basics`"]) go(("`Golang`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go(("`Golang`")) -.-> go/AdvancedTopicsGroup(["`Advanced Topics`"]) go/BasicsGroup -.-> go/variables("`Variables`") go/FunctionsandControlFlowGroup -.-> go/if_else("`If Else`") go/FunctionsandControlFlowGroup -.-> go/switch("`Switch`") go/AdvancedTopicsGroup -.-> go/time("`Time`") subgraph Lab Skills go/variables -.-> lab-149072{{"`Switch-Case Branch Statements in Golang`"}} go/if_else -.-> lab-149072{{"`Switch-Case Branch Statements in Golang`"}} go/switch -.-> lab-149072{{"`Switch-Case Branch Statements in Golang`"}} go/time -.-> lab-149072{{"`Switch-Case Branch Statements in Golang`"}} 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 expression. When the condition matches the value of a certain case statement, the corresponding case statement will be executed, and the program will then exit the current switch branch.

The values in the case statements must be of the same type as the condition expression.

The program will evaluate the case statements from top to bottom and execute the first matching case statement. After the execution is complete, it will exit the current switch branch.

The default statement is similar to the else statement. When no other case statements 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:

cd ~/project
touch switch.go
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.☀")
    }
}

Run the code:

go run switch.go

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.☀")
    }
}
go run switch.go

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 there is a sandstorm.

switch Statements with No Conditional Variable

The conditional variable in the switch statement is an optional parameter. When the conditional variable is omitted, the switch statement will behave similarly to an if-else statement.

We have rewritten the program to 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.")
    }
}
go run switch.go

After running the code, the output is as follows:

Today is Monday.

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

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(10)
        fallthrough
    case 3:
        fmt.Println(3)
    }
}
go run switch.go

After running the code, the output is as follows:

10
3

The switch branch outputs 10 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. You can write the initialization statement before the conditional variable, separated by a semicolon.

Quiz

Now, you 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.

cd ~/project
touch switch2.go

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 lab for modifying.

âœĻ Check Solution and Practice

Summary

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

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

Other Golang Tutorials you may like