How to Fix Go Interface Conversion and Type Assertion Panics
In this tutorial, you'll learn about How to Fix Go Interface Conversion and Type Assertion Panics. We cover key concepts, practical examples, and best practices.
Go panics with interface conversion: interface {} is X, not Y when a type assertion fails. This happens when code assumes the concrete type behind an interface without verifying it through the comma-ok pattern or type switch.
Quick Fix
Wrong
var val interface{} = "hello"
num := val.(int)
fmt.Println(num)
panic: interface conversion: interface {} is string, not int
The value is a string, but the code asserts it as an int.
Right
var val interface{} = "hello"
num, ok := val.(int)
if ok {
fmt.Println("Number:", num)
} else {
fmt.Println("Not a number")
}
Not a number
Fix with type switch
var val interface{} = "hello"
switch v := val.(type) {
case int:
fmt.Println("Integer:", v)
case string:
fmt.Println("String:", v)
default:
fmt.Println("Unknown type")
}
String: hello
Fix for interface assertions on function parameters
func handle(v interface{}) {
// Wrong: panics if v is not string
s := v.(string)
// Right:
s, ok := v.(string)
if !ok {
fmt.Println("Expected string, got different type")
return
}
fmt.Println("Got:", s)
}
handle(42)
Expected string, got different type
Prevention
- Always use the comma-ok pattern
val, ok := x.(T)for type assertions. - Use type switches for handling multiple possible types.
- Decode JSON into typed structs instead of
interface{}. - Avoid
interface{}parameters when concrete types are known. - Run
go vetto catch unchecked type assertions.
DodaTech Tools
Doda Browser's Go type checker flags unsafe type assertions and suggests the comma-ok pattern. DodaZIP archives Go source for dependency analysis. Durga Antivirus Pro detects type confusion vulnerabilities in Go code.
Common Mistakes with interface conversion
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro