Go:Go Switch Statement: No Break Required and Multiple Cases
Go•Switch Statement

Go Switch Statement: No Break Required and Multiple Cases

In Go, cases do not fall through by default (no break needed). Multiple values can be comma-separated.

Syntax

switch val { case "a", "b": // code default: // fallback }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
fallthroughKeywordExplicitly forces execution into the next case body.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import "fmt"

func main() {
    protocol := "POST"

    fmt.Printf("Evaluating protocol: %s\n", protocol)
    switch protocol {
    case "GET":
        fmt.Println("  Action: Retrieve existing data")
    case "POST", "PUT":
        fmt.Println("  Action: Mutate or save database record")
    case "DELETE":
        fmt.Println("  Action: Destroy record")
    default:
        fmt.Printf("  Action: Unsupported verb %s\n", protocol)
    }
}
Expected Output:
Evaluating protocol: POST
  Action: Mutate or save database record

How It Works: Step-by-Step

  • Lines 9-19: switch matches protocol without requiring explicit break statements.
  • Lines 12-13: Combines POST and PUT with comma separation.

Key Concepts

  • Go cases break automatically after executing.
  • To fall through into the next case, use the explicit fallthrough keyword.
  • Switch can be tagless (switch without expression), acting like clean if-else chains.

Common Mistake: Writing unnecessary break statements at the end of each case

Go does not require break in switch cases. While harmless, it is unidiomatic.

❌ Incorrect
case "A": doWork(); break; // Redundant break
✅ Correct
case "A": doWork();

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler