Type Assertions & Switches in Go

From the Go cheat sheet · Interfaces · verified Jul 2026

Type Assertions & Switches

Extract concrete types from interfaces

go
// Type assertion
var i interface{} = "hello"
s := i.(string)        // Panics if wrong type
s, ok := i.(string)    // Safe: ok = false if wrong

// Type switch
switch v := i.(type) {
case string:
    fmt.Println("string:", v)
case int:
    fmt.Println("int:", v)
default:
    fmt.Println("unknown")
}
📌 Always use the comma-ok form to avoid panics
💡 Type switches use .(type) — only works in switch statements
🎯 any is an alias for interface{} since Go 1.18
⚡ Type assertions work on interfaces, not concrete types

Continue with Go

Save the full cheat sheet or work through every related task.

More Go tasks

Back to the full Go cheat sheet