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