🔧 Error Fixes
· 1 min read

Go Interface Conversion Panic — How to Fix It


panic: interface conversion: interface {} is string, not int
panic: interface conversion: interface is nil, not main.MyType

You’re asserting an interface to a type it doesn’t hold, or the interface is nil.

Fix 1: Use Comma-Ok Pattern

// ❌ Direct assertion panics on wrong type
var i interface{} = "hello"
n := i.(int)  // 💥 panic

// ✅ Use comma-ok
n, ok := i.(int)
if !ok {
    fmt.Println("not an int")
}

Fix 2: Nil Interface

// ❌ Asserting on nil interface
var i interface{}
s := i.(string)  // 💥 panic

// ✅ Check for nil first
if i != nil {
    s, ok := i.(string)
}

Fix 3: Type Switch

// ✅ Handle multiple types cleanly
switch v := i.(type) {
case string:
    fmt.Println("string:", v)
case int:
    fmt.Println("int:", v)
case nil:
    fmt.Println("nil")
default:
    fmt.Printf("unexpected type: %T\n", v)
}

Fix 4: JSON Unmarshaling Returns Wrong Type

// ❌ JSON numbers become float64, not int
var data map[string]interface{}
json.Unmarshal([]byte(`{"count": 42}`), &data)
count := data["count"].(int)  // 💥 It's float64

// ✅ JSON numbers are float64
count := data["count"].(float64)
// Or unmarshal to a struct
type Response struct { Count int `json:"count"` }

Fix 5: Interface Not Implemented

// ❌ Type doesn't implement the interface
type Writer interface { Write([]byte) }
var w Writer = MyType{}  // 💥 Compile error if MyType doesn't have Write

// ✅ Implement the method
func (m MyType) Write(data []byte) {
    // implementation
}