ZetCode

Golang switch keyword

last modified May 7, 2025

This tutorial explains how to use the switch keyword in Go. We'll cover conditional logic basics with practical examples of switch statements.

The switch statement provides multi-way branching based on the value of an expression. It's cleaner than multiple if-else statements for many cases.

In Go, switch has several forms: expression switches, type switches, and can use fallthrough for special control flow. It's a versatile tool for decision-making.

Basic switch statement

The simplest form evaluates an expression and matches it against case values. This example demonstrates basic switch usage with numbers.

basic_switch.go
package main

import "fmt"

func main() {
    num := 3
    
    switch num {
    case 1:
        fmt.Println("One")
    case 2:
        fmt.Println("Two")
    case 3:
        fmt.Println("Three")
    default:
        fmt.Println("Unknown number")
    }
}

The switch evaluates num and executes the matching case. The default case runs if no matches are found. Cases don't need break statements.

Switch with expressions

Go allows expressions in case clauses. This example shows how to use comparisons in switch cases.

expression_switch.go
package main

import "fmt"

func main() {
    score := 85
    
    switch {
    case score >= 90:
        fmt.Println("Grade: A")
    case score >= 80:
        fmt.Println("Grade: B")
    case score >= 70:
        fmt.Println("Grade: C")
    case score >= 60:
        fmt.Println("Grade: D")
    default:
        fmt.Println("Grade: F")
    }
}

Without an expression after switch, it becomes like an if-else chain. The first true case executes, and the rest are skipped. This is very readable.

Switch with multiple values

Cases can test multiple comma-separated values. This example checks for vowels in a single switch statement.

multi_case.go
package main

import "fmt"

func main() {
    char := 'e'
    
    switch char {
    case 'a', 'e', 'i', 'o', 'u':
        fmt.Printf("%c is a vowel\n", char)
    case 'y':
        fmt.Printf("%c is sometimes a vowel\n", char)
    default:
        fmt.Printf("%c is a consonant\n", char)
    }
}

The first case matches any vowel. Multiple values make the code concise and easy to understand. The switch works with runes (characters) in this example.

Fallthrough in switch

Go's fallthrough transfers control to the next case. This example demonstrates its behavior.

fallthrough.go
package main

import "fmt"

func main() {
    num := 2
    
    switch num {
    case 1:
        fmt.Println("One")
    case 2:
        fmt.Println("Two")
        fallthrough
    case 3:
        fmt.Println("Three")
    case 4:
        fmt.Println("Four")
    default:
        fmt.Println("Unknown")
    }
}

When num is 2, it prints "Two" and then "Three" due to fallthrough. This is different from most languages where cases fall through by default.

Type switch

Go can switch on types using interface variables. This example identifies different types in a switch.

type_switch.go
package main

import "fmt"

func checkType(x interface{}) {
    switch x.(type) {
    case int:
        fmt.Println("Integer")
    case float64:
        fmt.Println("Float64")
    case string:
        fmt.Println("String")
    case bool:
        fmt.Println("Boolean")
    default:
        fmt.Println("Unknown type")
    }
}

func main() {
    checkType(42)
    checkType(3.14)
    checkType("hello")
    checkType(true)
}

The .(type) syntax is special for type switches. Each case checks for a specific type. This is powerful for handling different types dynamically.

Switch with initialization

Like if statements, switch can include an initialization statement. This example shows how to use this feature.

init_switch.go
package main

import (
    "fmt"
    "time"
)

func main() {
    switch hour := time.Now().Hour(); {
    case hour < 12:
        fmt.Println("Good morning!")
    case hour < 17:
        fmt.Println("Good afternoon!")
    default:
        fmt.Println("Good evening!")
    }
}

The hour variable is initialized before the switch expression. It's scoped to the switch block. This keeps related code together neatly.

Practical example: Command processor

This practical example shows a simple command processor using switch. It demonstrates real-world usage.

command_switch.go
package main

import (
    "fmt"
    "strings"
)

func processCommand(cmd string) {
    switch strings.ToLower(cmd) {
    case "start":
        fmt.Println("Starting system...")
    case "stop":
        fmt.Println("Stopping system...")
    case "status":
        fmt.Println("System is running")
    case "help", "?":
        fmt.Println("Available commands: start, stop, status, help")
    default:
        fmt.Println("Unknown command")
    }
}

func main() {
    processCommand("start")
    processCommand("HELP")
    processCommand("invalid")
}

The switch handles different commands case-insensitively. Multiple commands can map to the same action. Default handles invalid input gracefully.

Source

Go language specification

This tutorial covered the switch keyword in Go with practical examples of conditional logic in various scenarios.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Golang tutorials.