Go Type Switches: Syntax, Type Assertions, and Empty Interface Handling
Assertion forms that panic and those that do not, multi-type cases, typed nil interfaces, pointer-receiver method sets, and errors.As for wrapped errors.

A type assertion asks an interface value for the concrete type it holds; a type switch asks the same question in a form that can branch on several answers. Both work only on interfaces, both read the dynamic type stored inside, and both fail the same way at the edge: an assertion without the comma-ok form panics when the type does not match, and the panic is inside whichever goroutine made the call.
Quick Summary
x.(T)requiresxto be an interface; asserting on a concrete type is a compile error.- The single-result form panics on a mismatch; the comma-ok form (
v, ok := x.(T)) returns the zero value andfalse. switch v := x.(type)bindsvto the concrete type in each case, except in a multi-type case, wherevkeeps the interface's type.case nilmatches only a nil interface, not an interface holding a typed nil pointer.- A type assertion can target another interface, in which case it checks the method set rather than the concrete type.
- Whether a value's methods are found depends on the method set: a value stored as
Tcannot be asserted to an interface whose method has a pointer receiver. - For wrapped errors,
errors.Asis the correct tool; a plain type assertion only sees the outermost wrapper. - Type switches on a generic type parameter are rejected; converting through
anyis the documented workaround.
Basic syntax and type signatures
var x any = 42
n := x.(int) // 42
s, ok := x.(string) // "", false — no panic
// s2 := x.(string) // panic: interface conversion: interface {} is int, not string
switch v := x.(type) {
case int:
fmt.Println("int", v+1) // v is int
case string:
fmt.Println("string", len(v)) // v is string
case nil:
fmt.Println("nil interface")
default:
fmt.Printf("other %T\n", v) // v is any here? no: v is the interface type
}// Asserting to an interface checks the method set.
type Stringer interface{ String() string }
var y any = time.Now()
if st, ok := y.(fmt.Stringer); ok {
fmt.Println(st.String())
}
// Multiple types in one case: v keeps the interface type.
switch v := x.(type) {
case int, int64, float64:
fmt.Printf("number: %v (%T)\n", v, v) // v is any
}The compile-time restriction:
type MyInt int
var m MyInt
// _ = m.(int) // invalid type assertion: m.(int) (non-interface type MyInt on left)
_ = any(m).(int) // ok: 0? no — the dynamic type is main.MyInt, so this panicsAsserting a concrete value requires converting it to an interface first, and the assertion then compares the dynamic type — MyInt is not int, so the assertion fails even though both are integers underneath.
Comparison of discrimination techniques
| Technique | Input | Panics on mismatch | Sees wrapped errors | Cost | Use when |
|---|---|---|---|---|---|
x.(T) | interface | yes | n/a | low | the type is guaranteed |
v, ok := x.(T) | interface | no | n/a | low | the type may differ |
switch x.(type) | interface | no | n/a | low | several possible types |
errors.As(err, &t) | error | no | yes | low | an error may be wrapped |
errors.Is(err, sentinel) | error | no | yes | low | comparing with a known error |
reflect.TypeOf | any | no | n/a | high | dynamic, unknown sets of types |
The first three operate on the value's dynamic type. errors.As walks an error chain, which matters because the type assertion sees only the error that was returned, not the one wrapped inside it.
Practical edge cases and deep dives
1. The panic is not where the assertion is
func parse(v any) string {
return v.(string) // panics if v is anything else
}
func handler(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
http.Error(w, "bad request", http.StatusBadRequest)
}
}()
_ = parse(r.Context().Value(ctxKey("user")))
}The single-result form is reasonable only when a mismatch means a programming error — a value the code just stored under a private key, a type the function documented as required. Everywhere else, the comma-ok form or the two-result switch is the safer shape, because a recover in an HTTP handler converts an assertion bug into a 400 that hides the actual mistake. The %T verb is the cheap diagnostic: fmt.Printf("got %T\n", v) in a default branch turns a mystery panic into a named type.
2. Multi-type cases and the interface variable
func describe(x any) string {
switch v := x.(type) {
case nil:
return "nil"
case bool:
return fmt.Sprintf("bool %v", v)
case int, int8, int16, int32, int64:
return fmt.Sprintf("integer %v", v) // v is any
case string:
return "string of length " + strconv.Itoa(len(v))
case []byte:
return "bytes of length " + strconv.Itoa(len(v))
case fmt.Stringer:
return "stringer: " + v.String() // v is fmt.Stringer
case error:
return "error: " + v.Error()
default:
return fmt.Sprintf("unknown %T", v)
}
}Two rules operate here. In a case listing several types, v has the type of the switch expression (any), because the compiler cannot know which of the listed types matched — so len(v) would not compile. In a case naming a single interface, v has that interface type and its methods are callable. Cases are evaluated in order, and the first match wins, which is why a fmt.Stringer case placed before error changes the result for types implementing both.
A case nil is narrower than it looks: it matches only when the interface itself is nil. An interface holding a nil pointer is non-nil and matches the pointer's case.
var p *bytes.Buffer
var x any = p
fmt.Println(x == nil) // false: the interface has a type, bytes.Buffer, and a nil value
switch x.(type) {
case nil:
fmt.Println("nil interface")
case *bytes.Buffer:
fmt.Println("nil *bytes.Buffer") // this one matches
}3. Assertions and method sets: the pointer receiver trap
type Logger struct{ prefix string }
func (l *Logger) Log(msg string) { fmt.Println(l.prefix, msg) }
type Logging interface{ Log(string) }
var x any = Logger{prefix: "v"}
if l, ok := x.(Logging); ok {
l.Log("hello") // never runs: *Logger implements Logging, Logger does not
}
var y any = &Logger{prefix: "v"}
if l, ok := y.(Logging); ok {
l.Log("hello") // runs
}The assertion checks the dynamic type's method set. Logger has no Log method in its method set because the receiver is a pointer, so the assertion fails silently with ok == false — one of the quietest bugs in Go, since the comma-ok form turns a design mistake into a no-op. The same happens when a value is stored in an interface by a function that took it by value:
func store(m map[string]any, k string, v any) { m[k] = v }
store(m, "logger", Logger{}) // copies the value; assertion to Logging fails
store(m, "logger", &Logger{}) // pointer: assertion succeeds4. Wrapped errors need errors.As, not an assertion
type ValidationError struct {
Field string
Err error
}
func (e *ValidationError) Error() string { return e.Field + ": " + e.Err.Error() }
func (e *ValidationError) Unwrap() error { return e.Err }
func handle(err error) {
// Wrong: sees only the outermost type.
if ve, ok := err.(*ValidationError); ok {
fmt.Println("invalid field", ve.Field)
}
// Right: walks the chain.
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("invalid field", ve.Field)
}
// And for sentinels:
if errors.Is(err, io.EOF) {
fmt.Println("end of input")
}
}errors.As takes a pointer to the target type, because it needs somewhere to store the match; passing a non-pointer is a panic with a clear message (errors: target must be a non-nil pointer). The target must also be a type that implements error, so a wrapper struct with only an Unwrap method cannot be a target. When the wrapped value is a concrete error stored behind fmt.Errorf("%w"), errors.As unwraps through it, which a type assertion on the outer error never does.
5. Type switches on generic type parameters
func convert[T any](v T) string {
// switch any(v).(type) { ... } // ok
// switch v.(type) { ... } // error: cannot use type switch on type parameter value v
switch x := any(v).(type) {
case string:
return x
case int:
return strconv.Itoa(x)
case fmt.Stringer:
return x.String()
default:
return fmt.Sprintf("%v", x)
}
}A type switch needs a value with a dynamic type, and a type parameter's dynamic type is not known at compile time until the function is instantiated, so the language forbids it. Converting through any is the documented workaround, and it is exactly what the compiler would do internally. A better answer for most generic code is a constraint that names the behavior (T interface{ ~string | ~int }) rather than a runtime switch, since a type switch inside a generic function usually means the constraint was too weak.
Common mistakes and compiler errors
| Error or symptom | Cause | Fix |
|---|---|---|
invalid type assertion: x.(T) (non-interface type X on left) | asserting a concrete value | convert to any first, or use a type switch on an interface |
panic: interface conversion: interface {} is int, not string | single-result assertion with a mismatched type | comma-ok form |
cannot use type switch on type parameter value | type switch on a generic T | switch any(v).(type) |
impossible type assertion compile error | the asserted type cannot implement the interface | fix the assertion or the interface |
| Type assertion to an interface always returns false | value stored as T, method has a pointer receiver | store &T |
errors.As panic: target must be a non-nil pointer | passing the target by value | pass &target |
| A wrapped error is not found by an assertion | the error is wrapped | use errors.As |
case nil never matches | the interface holds a typed nil | compare the pointer, not the interface |
v is any inside a multi-type case | several types share the case | use a single type per case, or a type switch on each |
| Assertion succeeds but method call panics | the value is a nil pointer with methods | check for nil before use |
The choice between assertion forms is a choice about failure. x.(T) says "this cannot be anything else, and if it is, the program is wrong" — appropriate for values the same package produced and stored under a private key. v, ok := x.(T) says "handle what I expect and skip the rest" — appropriate at library boundaries, event handlers, and anything fed by external data, where the cost of a skipped branch is lower than the cost of a panic. A default branch that logs %T on the unexpected case is what turns the second form into something debuggable.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.