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.

GoData Integrity

Code

gosnippet
25 lines
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

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 :`.