iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

if / switch

Go has the C-family if + switch, both with init statements, plus the lovely tag-less switch for replacing if/else chains.

if, switch, type-switch, defer

EXAMPLE
package main

import (
    "errors"
    "fmt"
    "strconv"
)

func main() {
    // 1) if with an init clause — common for error checks
    if n, err := strconv.Atoi("42"); err != nil {
        fmt.Println("bad number:", err)
    } else if n > 100 {
        fmt.Println("big")
    } else {
        fmt.Println("ok", n)
    }

    // 2) Tag-less switch — replaces if/else chains
    role := "admin"
    switch {
    case role == "admin":
        fmt.Println("full access")
    case role == "editor":
        fmt.Println("edit only")
    case role == "member":
        fmt.Println("read only")
    default:
        fmt.Println("banned")
    }

    // 3) Tagged switch — multiple values per case, no fallthrough
    switch day := "Sat"; day {
    case "Sat", "Sun":
        fmt.Println("weekend")
    case "Mon", "Tue", "Wed", "Thu", "Fri":
        fmt.Println("weekday")
    }

    // 4) Type-switch — runtime dispatch on dynamic type
    var any any = 42
    switch v := any.(type) {
    case int:
        fmt.Println("int:", v*2)
    case string:
        fmt.Println("string:", len(v))
    case error:
        fmt.Println("err:", v.Error())
    default:
        fmt.Printf("%T %v\n", v, v)
    }

    // 5) errors.Is / errors.As — modern error switching
    var notFound = errors.New("not found")
    err := find()
    if errors.Is(err, notFound) {
        fmt.Println("gone")
    }
}

func find() error { return errors.New("not found") }

Why it matters

Go’s switch doesn’t fall through by default — the opposite of C. Use fallthrough on the rare occasion you actually want it; otherwise enjoy not having to type break.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
if x := compute(); x > 10 {
    fmt.Println("big")
} else {
    fmt.Println("small")
}

switch day {
case "Sat", "Sun":
    fmt.Println("weekend")
default:
    fmt.Println("weekday")
}
Try it Yourself »

Discussion

Loading…