Switch Statement in Go

Golang like most other programming languages ​​has the switch statement . The switch statement in Golang  allows you to evaluate a variable or expression in multiple cases and is often used when writing multiple if-else statements makes the code look ugly and repetitive.

Switch Statement in Go

In Go, a switch statement is a multi-directional branching statement that effectively directs execution based on the value (or type) of an expression. There are two main types of switch statements in Go :

  • Expression Switch
  • Type Switch

For example:

package main
import "fmt"

func main() {
    day := 4
    switch day {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
    case 4:
        fmt.Println("Thursday")
    case 5:
        fmt.Println("Friday")
    default:
        fmt.Println("Invalid day")
    }
}

Switch statement syntax in Golang

switch optstatement; optexpression {
case expression1:
    // Khối code
case expression2:                                                          # Expression Switch
    // Khối code
default:
    // Khối code
}

switch var := interfaceValue.(type) {
case type1:
    // Khối code
case type2:                                                                    # Type Switch
    // Khối code
default:
    // Khối code
}

Expression Switch

Expression Switch evaluates an expression and switches to a case based on the value of that expression. If no expression is provided, switch defaults to true .

Syntax

switch optstatement; optexpression {
case expression1:
    // Khối code
case expression2:
    // Khối code
default:
    // Khối code
}

optstatement: Optional statement (e.g. variable declaration).
optexpression: Optional expression (if omitted, defaults to true ).

Example with optional command

Here we introduce an optional statement that declares a variable day . The switch statement then evaluates day under various cases.

package main
import "fmt"
func main() {
    switch day := 4; day {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
    case 4:
        fmt.Println("Thursday")
    case 5:
        fmt.Println("Friday")
    default:
        fmt.Println("Invalid day")
    }
}

Result:

Thursday

Example with optional Expression

If no expression is specified, the switch statement in Golang will assume the expression is true. This allows us to use boolean conditions in case statements.

package main
import "fmt"

func main() {
    day := 4

    switch {
    case day == 1:
        fmt.Println("Monday")
    case day == 4:
        fmt.Println("Thursday")
    case day > 5:
        fmt.Println("Weekend")
    default:
        fmt.Println("Invalid day")
    }
}

Result

Thursday

Type Switch

Type Switch is used to branch on the type of an interface value, rather than its value. This is especially useful when dealing with variables of unknown type.

Syntax

switch var := interfaceValue.(type) {
case type1:
    // Khối code
case type2:
    // Khối code
default:
    // Khối code
}

For example:

This example uses the same day variable but wrapped in interface{} to illustrate type casting.

package main
import "fmt"
func main() {
    var day interface{} = 4
    switch v := day.(type) {
    case int:
        switch v {
        case 1:
            fmt.Println("Monday")
        case 2:
            fmt.Println("Tuesday")
        case 3:
            fmt.Println("Wednesday")
        case 4:
            fmt.Println("Thursday")
        case 5:
            fmt.Println("Friday")
        default:
            fmt.Println("Invalid day")
        }
    default:
        fmt.Printf("Unknown type: %T\n", v)
    }
}

Result:

Thursday

golang,golang switch command,switch command in golang,golang switch tutorial,how to use switch in golang,go,go programming

Leave a Comment

What Young Riders Should Know About Moving Their Motorcycles Across Cities

What Young Riders Should Know About Moving Their Motorcycles Across Cities

Long-distance travel can involve heavy traffic, changing weather conditions, and rider fatigue. If you are also dealing with the responsibilities of moving home, such as packing belongings or coordinating accommodation, a long ride may add unnecessary pressure to an already busy schedule.

Solving Microsoft Teams Shortcut Error Not Opening

Solving Microsoft Teams Shortcut Error Not Opening

Tired of Microsoft Teams shortcut error preventing you from opening the app? Follow our expert, step-by-step guide with the latest fixes for instant resolution. Works on Windows, Mac & web – no tech skills needed!

Solving Microsoft Teams Task Management Sync Error

Solving Microsoft Teams Task Management Sync Error

Tired of Microsoft Teams Task Management Sync Error halting your workflow? Follow our proven, step-by-step fixes to resolve sync issues fast and restore seamless task collaboration. No tech expertise needed!

Troubleshooting Microsoft Teams Wiki Error Formatting

Troubleshooting Microsoft Teams Wiki Error Formatting

Struggling with Microsoft Teams Wiki Error Formatting? This step-by-step guide reveals proven fixes for common wiki tab issues, ensuring smooth editing and collaboration in Teams. Get back to productive wikis fast!

How to Fix Microsoft Teams Installation Error for Linux

How to Fix Microsoft Teams Installation Error for Linux

Struggling with Microsoft Teams installation error on Linux? Discover step-by-step fixes for Ubuntu, Fedora & more. Resolve dependency issues, crashes, and errors quickly with our ultimate guide. Get Teams running smoothly today!

Solving Microsoft Teams Error Page Not Loading

Solving Microsoft Teams Error Page Not Loading

Struggling with Microsoft Teams "Error Page" not loading? Get step-by-step fixes for desktop, web, and mobile. Solve Microsoft Teams Error Page issues quickly and resume seamless teamwork today.

Solving Microsoft Teams Error Screenshot Issues

Solving Microsoft Teams Error Screenshot Issues

Tired of Microsoft Teams "Error Screenshot" blocking your workflow? Get proven, step-by-step solutions to resolve screenshot errors in Teams instantly and boost productivity. No tech skills needed!

How to Fix Microsoft Teams Error U User

How to Fix Microsoft Teams Error U User

Tired of Microsoft Teams "Error U" User blocking your chats? Get proven, step-by-step fixes to clear cache, reset, and restore seamless collaboration instantly.

Where are Microsoft Teams Registry Keys Located on Windows 11?

Where are Microsoft Teams Registry Keys Located on Windows 11?

Unlock the precise locations of Microsoft Teams registry keys on Windows 11. Step-by-step guide to find, access, and safely tweak them for optimal performance and troubleshooting. Essential for IT pros and Teams enthusiasts.

How to Fix Microsoft Teams Training Error Video Lag

How to Fix Microsoft Teams Training Error Video Lag

Tired of Microsoft Teams "Training Error" Video Lag ruining your meetings? Follow our step-by-step guide with the latest fixes for smooth video calls—no more frustration!