interface conversion

Go Programming Language

Severity: Moderate

What it means

The message names the types, such as panic: interface conversion: interface {} is string, not int. The value held a string, and the code asserted int.
The Go spec: if a type assertion x.(T) is false, a run-time panic occurs.
Asserting an interface the value doesn't implement, the message ends with the missing method, as in is not io.Reader: missing method Read.

Affected Models

  • Go programs at run time

How to Fix It

  1. Use the two-value form when the type isn't certain: v, ok := x.(int). The Go spec: then no run-time panic occurs, and ok is false.

  2. Several possible types? Use a type switch: switch v := x.(type) { case int: ... case string: ... }

  3. Data decoded from JSON into an any or interface{}? Go's docs: numbers come back as float64, arrays as []any, and objects as map[string]any. Assert those types, or decode into a struct.

  4. The same type name on both sides, with (types from different packages) after it? Two packages each define a type by that name. Use the one from the package the value really comes from.