Go

Type Switches

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
When you have an `interface{}` (or any) and need to dispatch on its underlying type, use `switch v := x.(type)`. Cleaner than a chain of type-assertions.
Go
Raw
package main

import "fmt"

func describe(x any) string {
    switch v := x.(type) {
    case int:
        return fmt.Sprintf("int %d", v)
    case string:
        return fmt.Sprintf("string of length %d: %q", len(v), v)
    case bool:
        return fmt.Sprintf("bool: %t", v)
    case []int:
        return fmt.Sprintf("[]int with %d elements", len(v))
    case nil:
        return "nil"
    default:
        return fmt.Sprintf("unknown type %T", v)
    }
}

func main() {
    for _, x := range []any{42, "hello", true, []int{1, 2, 3}, 3.14, nil} {
        fmt.Println(describe(x))
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.