Ad Space — Top Banner

interface conversion panic

Go Programming Language

Severity: Critical

What it means

Go panics when you assert an interface to the wrong concrete type.
The value inside the interface is not what you expected.
Use the two-value form of type assertion to avoid the crash.

Affected Models

  • Go 1.21
  • Go 1.22
  • Go 1.23
  • Go 1.24

Common Causes

  • Using a single-value type assertion (x.(T)) when the type does not match
  • Asserting a nil interface to any concrete type
  • Assuming a function returns a specific type when it returns interface{}
  • Type mismatch after unmarshaling JSON into an interface{} value
  • Not checking the dynamic type of an interface before asserting it

How to Fix It

  1. Switch from the single-value form (v := x.(T)) to the two-value form.

    Use: v, ok := x.(T).
    If ok is false, the assertion failed — handle it without a crash.

  2. Check if the interface value is nil before asserting: if x == nil { ... }

    Asserting any type from a nil interface always panics.
    Guard against nil first.

  3. Use a type switch to handle multiple possible types safely.

    switch v := x.(type) { case string: ... case int: ... default: ... } is the idiomatic Go approach.

  4. When working with JSON unmarshaled into interface{}, remember numbers become float64.

    var data interface{}; json.Unmarshal(...) — a JSON number will be float64, not int.

  5. Add logging or fmt.Printf("%T", x) to print the actual dynamic type at runtime.

    This helps you see what type is actually stored in the interface when debugging.

When to Call a Professional

If this panic appears in code that processes user-supplied data, have a senior developer review the type handling logic.
Improper type assertions on untrusted input can hide deeper design issues.

Frequently Asked Questions

What is the difference between a type assertion and a type conversion in Go?

A type assertion (x.(T)) extracts the concrete type from an interface — it can panic.
A type conversion (T(x)) converts between compatible types at compile time — it cannot panic.
Always use the two-value form for type assertions.

Why does 'interface conversion: interface is nil, not string' happen?

You tried to assert a nil interface to string.
Nil interfaces hold no value at all — you cannot assert them to anything.
Always check for nil before asserting.

Can I assert to an interface type instead of a concrete type?

Yes.
You can assert x.(SomeInterface) to check if x implements SomeInterface.
Use the two-value form to do it safely.
This is useful when you want to check for optional behavior.