BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Switch Expressions

Go 1.23

Go's `switch` statement is more flexible than C's. It handles multiple cases, supports expressions (not just constants), and eliminates implicit fallthrough. This example covers basic switches, multiple-value cases, and type switches.

Code

package main

import (
    "fmt"
    "time"
)

func main() {
    // 1. Basic Switch
    // Implicit break: Go only runs the selected case.
    i := 2
    fmt.Print("Write ", i, " as ")
    switch i {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    case 3:
        fmt.Println("three")
    }

    // 2. Multiple Expressions in Case
    // You can separate values with commas.
    day := time.Now().Weekday()
    switch day {
    case time.Saturday, time.Sunday:
        fmt.Println("It's the weekend")
    default:
        fmt.Println("It's a weekday")
    }

    // 3. Switch without Expression (Tagless)
    // Acts like a long if-else chain. Clean way to write complex logic.
    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("Good morning!")
    case t.Hour() < 17:
        fmt.Println("Good afternoon!")
    default:
        fmt.Println("Good evening!")
    }

    // 4. Type Switch
    // Discover the dynamic type of an interface value.
    whatAmI := func(i interface{}) {
        switch t := i.(type) {
        case bool:
            fmt.Println("I'm a bool")
        case int:
            fmt.Println("I'm an int")
        default:
            fmt.Printf("Don't know type %T\n", t)
        }
    }
    whatAmI(true)
    whatAmI(1)
    whatAmI("hello")
}

Explanation

The switch statement in Go is a powerful control structure that improves upon the traditional C/C++ switch. The most notable difference is that there is no implicit fallthrough. In Go, only the matched case is executed, so you don't need to write break at the end of every case. If you actually want fallthrough behavior, you must explicitly use the fallthrough keyword.

Go switches are also more flexible in what they can match. You can use multiple values in a single case (separated by commas), and you can even omit the switch expression entirely. A "tagless" switch (switch { ... }) functions exactly like a chain of if-else if-else statements but is often cleaner to read.

Another unique feature is the type switch. This allows you to compare the dynamic type of an interface variable against multiple types, which is essential when working with generic data or parsing JSON.

  • No Fallthrough: Safer by default; use fallthrough if needed.
  • Multiple Values: case 1, 2, 3: handles multiple inputs.
  • Tagless Switch: Replaces complex if-else chains.
  • Type Switch: switch v.(type) checks runtime types.

Code Breakdown

13-20
A standard switch statement. Unlike C, once 'case 2' matches and prints "two", execution stops. It does NOT fall through to 'case 3'.
26
Multiple values in a single case. This line checks if 'day' is either Saturday OR Sunday. This is much more concise than writing two separate cases with the same body.
35
A tagless switch. Since there is no variable after 'switch', each case must be a boolean expression. Go evaluates them top-to-bottom until one is true.
47
The type switch syntax 'i.(type)'. This is special syntax only valid inside a switch statement. It allows you to branch logic based on the underlying type of an interface value.