Interface Equality Panics On Uncomparable Types
Comparing two interface values whose dynamic type is a slice or map panics at runtime; guard the comparison with recover or a type switch.
Code
package main
import "fmt"
func equal(a, b any) (answer string) {
// interface equality compares dynamic types then values; slices, maps and
// funcs are uncomparable, so comparing two of them panics instead of
// returning false — recover turns that panic into an observable result
defer func() {
if r := recover(); r != nil {
answer = fmt.Sprintf("panic: %v", r)
}
}()
if a == b {
return "equal"
}
return "different"
}
func main() {
fmt.Println("int :", equal(42, 42))
fmt.Println("string:", equal("go", "go"))
fmt.Println("slice :", equal([]int{1, 2}, []int{1, 2}))
fmt.Println("map :", equal(map[string]int{"a": 1}, map[string]int{"a": 1}))
}Inside the snippet
Interface Equality Panics On Uncomparable Types is built around the functions equal and main.
defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Points of care
- No package manager runs in the flow — every call lands on a built-in API.
Putting it to use
Signature: func equal(a, b any) (answer string)
Output lines are prefixed (int :, string:, slice :), making the effect of each step easy to see.
Running the file executes main, which drives equal in order.
The core lines of the flow
if r := recover(); r != nil {
answer = fmt.Sprintf("panic: %v", r)
}
func main() {
fmt.Println("int :", equal(42, 42))
fmt.Println("string:", equal("go", "go"))
fmt.Println("slice :", equal([]int{1, 2}, []int{1, 2}))
fmt.Println("map :", equal(map[string]int{"a": 1}, map[string]int{"a": 1}))
}
return "different"
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Interface Equality Panics On Uncomparable Types print when run?
- Running the file directly is enough — expect labeled output lines such as `int :`, `string:`, `slice :`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.