Type Assertions — Find the Bug¶
Bug 1 — Single-value panic¶
Bug: Panic — string, not int. Fix:n, ok := i.(int); if !ok { ... }. Bug 2 — Wrapped error¶
type MyErr struct{}
func (e *MyErr) Error() string { return "err" }
err := fmt.Errorf("wrap: %w", &MyErr{})
e, ok := err.(*MyErr)
ok=false. Wrapped — direct assertion ishlamaydi. Fix: var e *MyErr; errors.As(err, &e). Bug 3 — Pointer mismatch¶
Bug:ok=false. The value is T, not T. Fix:* v, ok := i.(T) or var i any = &T{}. Bug 4 — nil interface assertion¶
Bug: Panic. Fix: Two-value form.Bug 5 — Polymorphism via assertion¶
func process(x any) {
if a, ok := x.(*A); ok { a.Method() }
if b, ok := x.(*B); ok { b.Method() }
if c, ok := x.(*C); ok { c.Method() }
}
Bug 6 — Interface conversion forgotten¶
type Reader interface { Read([]byte) (int, error) }
type Closer interface { Close() error }
func handleReader(r Reader) {
r.Close() // Reader has no Close method
}
Bug 7 — JSON number type¶
var data any
json.Unmarshal([]byte(`{"age": 30}`), &data)
m := data.(map[string]any)
age := m["age"].(int) // ?
float64. Fix: age := int(m["age"].(float64)). Bug 8 — Map value missing¶
Bug:m["missing"] nil interface — single-value panic. Fix: Bug 9 — Type assertion forwarding¶
Not a bug, but a style issue: uses instead. Fix: process(s). Bug 10 — Single var multiple assertion¶
Bug:v int. String assign qilolmaysiz. Fix: Yoki — type switch.
Bug 11 — Errors comparison¶
Bug: Wrapped error-larni topmaydi. Fix:if errors.Is(err, ErrNotFound) { ... }. Bug 12 — Generic type assertion¶
Bug: Compile error — type parameter assertion (Go 1.18 limitation). Fix: Use a type switch or convert to a concrete type.Actually (Go 1.18+ — this is OK):