Start Coding

Topics

Go Switch Statement

The switch statement in Go is a powerful control flow mechanism that allows you to execute different code blocks based on the value of an expression. It provides a cleaner and more efficient alternative to multiple if-else statements.

Basic Syntax

The basic syntax of a Go switch statement is as follows:

switch expression {
case value1:
    // code block
case value2:
    // code block
default:
    // code block
}

The expression is evaluated once, and its value is compared against the values specified in each case. When a match is found, the corresponding code block is executed.

Features and Usage

1. Multiple Cases

Go allows you to specify multiple cases for a single code block:

switch day {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
    fmt.Println("It's a weekday")
case "Saturday", "Sunday":
    fmt.Println("It's the weekend")
default:
    fmt.Println("Invalid day")
}

2. Expression-less Switch

Go supports switch statements without an expression, which can be used as an alternative to if-else chains:

switch {
case score >= 90:
    fmt.Println("A")
case score >= 80:
    fmt.Println("B")
case score >= 70:
    fmt.Println("C")
default:
    fmt.Println("F")
}

3. Fallthrough

Unlike other languages, Go's switch cases break automatically. To execute the next case, use the fallthrough keyword:

switch num {
case 1:
    fmt.Println("One")
    fallthrough
case 2:
    fmt.Println("Two")
case 3:
    fmt.Println("Three")
}

Best Practices

  • Use switch statements when you have multiple conditions based on a single variable or expression.
  • Prefer switch over long if-else chains for better readability and performance.
  • Use the default case to handle unexpected values or provide a fallback option.
  • Avoid overusing fallthrough, as it can make the code harder to understand.

Related Concepts

To further enhance your understanding of Go control flow, explore these related topics:

By mastering the switch statement and other control flow mechanisms, you'll be able to write more efficient and readable Go code.