Why This Happens
When you assert an interface value to a concrete type with x.(int) and the actual value is not an int, Go panics. The safe way is to use the two-value form: val, ok := x.(int), where ok is false if the assertion fails instead of panicking.
The Problem
func process(val interface{}) {
n := val.(int) // panics if val is not int
fmt.Println(n * 2)
}
func main() {
process("hello") // panic: interface conversion
}The Fix
func process(val interface{}) {
n, ok := val.(int)
if !ok {
fmt.Println("expected int, got something else")
return
}
fmt.Println(n * 2)
}Step-by-Step Fix
- 1
Identify the assertion
Find the type assertion in your code and check what concrete type is actually stored in the interface.
- 2
Use the two-value form
Change x.(T) to val, ok := x.(T) to prevent panics on wrong types.
- 3
Consider a type switch
If the interface can hold multiple types, use a type switch to handle each case explicitly.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free