Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readGo
#Go#Interfaces#Type System
3D illustration of an any value entering a multi-way type switch scanner that routes to concrete type tracks

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) requires x to 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 and false.
  • switch v := x.(type) binds v to the concrete type in each case, except in a multi-type case, where v keeps the interface's type.
  • case nil matches 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 T cannot be asserted to an interface whose method has a pointer receiver.
  • For wrapped errors, errors.As is the correct tool; a plain type assertion only sees the outermost wrapper.
  • Type switches on a generic type parameter are rejected; converting through any is the documented workaround.

Basic syntax and type signatures

go
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 }
go
// 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:

go
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 panics

Asserting 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

TechniqueInputPanics on mismatchSees wrapped errorsCostUse when
x.(T)interfaceyesn/alowthe type is guaranteed
v, ok := x.(T)interfacenon/alowthe type may differ
switch x.(type)interfacenon/alowseveral possible types
errors.As(err, &t)errornoyeslowan error may be wrapped
errors.Is(err, sentinel)errornoyeslowcomparing with a known error
reflect.TypeOfanynon/ahighdynamic, 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

go
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

go
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.

go
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

go
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:

go
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 succeeds

4. Wrapped errors need errors.As, not an assertion

go
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

go
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 symptomCauseFix
invalid type assertion: x.(T) (non-interface type X on left)asserting a concrete valueconvert to any first, or use a type switch on an interface
panic: interface conversion: interface {} is int, not stringsingle-result assertion with a mismatched typecomma-ok form
cannot use type switch on type parameter valuetype switch on a generic Tswitch any(v).(type)
impossible type assertion compile errorthe asserted type cannot implement the interfacefix the assertion or the interface
Type assertion to an interface always returns falsevalue stored as T, method has a pointer receiverstore &T
errors.As panic: target must be a non-nil pointerpassing the target by valuepass &target
A wrapped error is not found by an assertionthe error is wrappeduse errors.As
case nil never matchesthe interface holds a typed nilcompare the pointer, not the interface
v is any inside a multi-type caseseveral types share the caseuse a single type per case, or a type switch on each
Assertion succeeds but method call panicsthe value is a nil pointer with methodscheck 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 tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.