Comparing Uncomparable Types

invalid operation: s1 == s2 (struct containing []int cannot be compared)

Quick Answer

Structs containing slices, maps, or functions cannot be compared with == directly. Use reflect.DeepEqual or write a custom comparison.

Why This Happens

Go's == operator works on comparable types: numbers, strings, booleans, pointers, channels, arrays (of comparable types), and structs (with only comparable fields). Slices, maps, and functions are not comparable. Structs containing these types inherit the restriction.

The Problem

type Config struct {
    Ports []int
}

func main() {
    a := Config{Ports: []int{80, 443}}
    b := Config{Ports: []int{80, 443}}
    fmt.Println(a == b) // invalid operation
}

The Fix

import "reflect"

func main() {
    a := Config{Ports: []int{80, 443}}
    b := Config{Ports: []int{80, 443}}
    fmt.Println(reflect.DeepEqual(a, b)) // true
}

Step-by-Step Fix

  1. 1

    Identify the uncomparable field

    Check which struct field contains a slice, map, or function that prevents comparison.

  2. 2

    Use reflect.DeepEqual

    For quick comparison, use reflect.DeepEqual(a, b). Note it is slower than manual comparison.

  3. 3

    Write custom comparison

    For performance-critical code, write a custom Equal method that compares fields individually.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free