</>
Skip to content
Go lessons (13/34)

Go — Switch

Basic switch

package main

import "fmt"

func main() {
    day := "Monday"

    switch day {
    case "Monday":
        fmt.Println("Start of week")
    case "Friday":
        fmt.Println("Almost weekend")
    case "Saturday", "Sunday":
        fmt.Println("Weekend!")
    default:
        fmt.Println("Midweek")
    }
}

Expression-less switch

score := 85

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

Switch with init statement

switch status := getStatus(); {
case status == 200:
    fmt.Println("OK")
case status == 404:
    fmt.Println("Not Found")
case status >= 500:
    fmt.Println("Server Error")
}

Type switch

var x interface{} = "hello"

switch v := x.(type) {
case int:
    fmt.Printf("Integer: %d\n", v)
case string:
    fmt.Printf("String: %s\n", v)
case bool:
    fmt.Printf("Boolean: %t\n", v)
default:
    fmt.Printf("Unknown: %T\n", v)
}

fallthrough

n := 2

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

Multiple cases

char := 'a'

switch char {
case 'a', 'e', 'i', 'o', 'u':
    fmt.Println("Vowel")
default:
    fmt.Println("Consonant")
}

Switch with channels

ch := make(chan int, 1)
ch <- 42

select {
case v := <-ch:
    fmt.Println("Received:", v)
default:
    fmt.Println("No value")
}

Best practices

  • Use switch over long if-else if chains
  • Avoid fallthrough — it's rarely needed
  • Use expression-less switch for range-based logic
  • Use select for channel operations

Mini Practice

Write Go code that:

  1. Uses switch to classify a number range
  2. Uses type switch on an interface{}
  3. Uses fallthrough intentionally
  4. Combines multiple cases in one case clause

Up Next

In the next lesson, you'll learn about Loops — Go's only loop construct.

Related Topics

Frequently Asked Questions about Switch

What is Switch in Go?

Switch is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Switch?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Switch.

Why is Switch important in Go?

Switch is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.