Equality and comparison

suggest change

Go has two kinds of comparison operators:

What can be compared is decided at compile time by the type, and the rules are stricter than in many languages. There's no operator overloading, so you can't make == do something custom for your type. For anything beyond the built-in rules you use functions from the standard library (slices.Equal, maps.Equal, cmp.Compare, reflect.DeepEqual) or write an Equal method.

Which types are comparable

type == < notes
booleans yes no
integers, floats, complex yes yes (not complex) NaN is not equal to itself
strings yes yes byte-wise
pointers yes no equal if they point to the same variable
channels yes no equal if created by the same make call
interfaces yes no can panic at runtime
arrays if element type is comparable no element by element
structs if all fields are comparable no field by field
slices, maps, functions only with nil no

Here are the basic cases:

package main

import "fmt"

type Point struct {
	X, Y int
}

func main() {
	fmt.Println(3 == 3.0, "go" == "Go", 'a' < 'b')

	a := [3]int{1, 2, 3}
	b := [3]int{1, 2, 3}
	fmt.Println(a == b)

	p1 := Point{1, 2}
	p2 := Point{1, 2}
	fmt.Println(p1 == p2, &p1 == &p2)

	pp := &p1
	fmt.Println(pp == &p1)

	ch1 := make(chan int)
	ch2 := ch1
	fmt.Println(ch1 == ch2, ch1 == make(chan int))

	// struct and array values can be map keys
	visited := map[Point]bool{}
	visited[Point{1, 2}] = true
	fmt.Println(visited[p2])
}
true false true
true
true false
true
true false
true

Things to notice:

Comparing strings is covered in more detail in Compare strings.

Slices, maps and functions

Slices, maps and functions can only be compared to nil. A struct or array that contains them is not comparable either. These are compile errors:

type Config struct {
	Name string
	Tags []string
}

func main() {
	a := []int{1}
	b := []int{1}
	fmt.Println(a == b)

	m1 := map[string]int{}
	m2 := map[string]int{}
	fmt.Println(m1 == m2)

	f := func() {}
	fmt.Println(f == nil, f == f)

	c1, c2 := Config{}, Config{}
	fmt.Println(c1 == c2)
}
./main.go:13:14: invalid operation: a == b (slice can only be compared to nil)
./main.go:17:14: invalid operation: m1 == m2 (map can only be compared to nil)
./main.go:20:24: invalid operation: f == f (func can only be compared to nil)
./main.go:23:14: invalid operation: c1 == c2 (struct containing []string cannot be compared)

This is a deliberate design choice: for a slice it's not obvious whether == should mean "same backing array" or "same elements", so Go makes you say what you mean.

To compare contents, use the generic functions from the slices and maps packages:

package main

import (
	"bytes"
	"fmt"
	"maps"
	"reflect"
	"slices"
	"strings"
)

func main() {
	a := []int{1, 2, 3}
	b := []int{1, 2, 3}
	fmt.Println(slices.Equal(a, b))

	var nilSlice []int
	empty := []int{}
	fmt.Println(nilSlice == nil, empty == nil, slices.Equal(nilSlice, empty))

	names1 := []string{"Ann", "BOB"}
	names2 := []string{"ann", "bob"}
	fmt.Println(slices.EqualFunc(names1, names2, strings.EqualFold))

	fmt.Println(bytes.Equal([]byte("abc"), []byte("abc")))

	m1 := map[string]int{"a": 1, "b": 2}
	m2 := map[string]int{"b": 2, "a": 1}
	fmt.Println(maps.Equal(m1, m2))

	fmt.Println(reflect.DeepEqual(a, b))
	fmt.Println(reflect.DeepEqual(nilSlice, empty))

	type Config struct {
		Name string
		Tags []string
		Opts map[string]bool
	}
	c1 := Config{"srv", []string{"x"}, map[string]bool{"debug": true}}
	c2 := Config{"srv", []string{"x"}, map[string]bool{"debug": true}}
	fmt.Println(reflect.DeepEqual(c1, c2))
}
true
true false true
true
true
true
true
false
true

reflect.DeepEqual

reflect.DeepEqual recursively compares any two values, including structs that contain slices and maps. It's convenient but has drawbacks:

In tests, github.com/google/go-cmp is a popular alternative that also prints a readable diff:

if diff := cmp.Diff(want, got); diff != "" {
	t.Errorf("result mismatch (-want +got):\n%s", diff)
}

Comparing interfaces

Two interface values are equal if both are nil, or if they have identical dynamic types and their dynamic values are equal:

package main

import "fmt"

func main() {
	var x, y any
	fmt.Println(x == y) // both nil

	x, y = 5, 5
	fmt.Println(x == y)

	x, y = 5, int64(5)
	fmt.Println(x == y) // different dynamic types

	x = "hello"
	fmt.Println(x == "hello") // compare interface with concrete value

	defer func() {
		fmt.Println("recovered:", recover())
	}()
	x, y = []int{1}, []int{1}
	fmt.Println(x == y)
}
true
true
false
true
recovered: runtime error: comparing uncomparable type []int

Interface types are comparable at compile time, but if the dynamic type isn't comparable the comparison panics at runtime. The same happens when you use such a value as a map key, e.g. map[any]int{}[[]int{1}] = 1.

Interface holding a nil pointer

An interface is nil only if both its type and value are nil. An interface that holds a typed nil pointer is not equal to nil. This is a classic bug with errors:

package main

import (
	"errors"
	"fmt"
)

type MyError struct{}

func (*MyError) Error() string { return "my error" }

func mayFail(fail bool) error {
	var err *MyError
	if fail {
		err = &MyError{}
	}
	return err // BUG: returns non-nil interface holding a nil pointer
}

func main() {
	err := mayFail(false)
	fmt.Println(err == nil)
	fmt.Printf("%T %v\n", err, err == (*MyError)(nil))

	var target *MyError
	fmt.Println(errors.As(err, &target))
}
false
*main.MyError true
true

The fix is to return a literal nil in the success path: if !fail { return nil }. Never return a concrete error pointer type through an error interface without checking it.

For errors in general, prefer errors.Is over ==: err == ErrNotFound fails once the error has been wrapped with fmt.Errorf("...: %w", err), while errors.Is(err, ErrNotFound) unwraps the chain. See Handling an error.

Floating-point numbers

Floats follow IEEE 754, which leads to a few surprises:

package main

import (
	"fmt"
	"math"
)

func almostEqual(a, b, tolerance float64) bool {
	if a == b {
		return true
	}
	diff := math.Abs(a - b)
	scale := math.Max(math.Abs(a), math.Abs(b))
	return diff <= tolerance*scale
}

func main() {
	x, y := 0.1, 0.2
	sum := x + y
	fmt.Println(sum == 0.3)
	fmt.Println(sum, almostEqual(sum, 0.3, 1e-9))

	// constant expressions are computed exactly at compile time
	fmt.Println(0.1+0.2 == 0.3)

	nan := math.NaN()
	fmt.Println(nan == nan, nan != nan, math.IsNaN(nan))

	negZero := math.Copysign(0, -1)
	fmt.Println(negZero == 0, math.Signbit(negZero))

	m := map[float64]int{}
	m[nan] = 1
	m[nan] = 2
	fmt.Println(len(m), m[nan])
}
false
0.30000000000000004 true
true
false true true
true true
2 0

For exact decimal arithmetic (e.g. money) use integers (cents) or math/big, see big.Int, big.Float, and big.Rat.

See also Floating-point numbers.

Types with an Equal or Cmp method

Some standard library types must not be compared with == even though they're comparable. They provide a method instead:

package main

import (
	"fmt"
	"math/big"
	"time"
)

func main() {
	t1 := time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC)
	loc := time.FixedZone("CEST", 2*60*60)
	t2 := t1.In(loc)
	fmt.Println(t1 == t2, t1.Equal(t2), t1.Compare(t2))

	now := time.Now()
	stripped := now.Round(0) // removes monotonic clock reading
	fmt.Println(now == stripped, now.Equal(stripped))

	a := big.NewInt(42)
	b := big.NewInt(42)
	fmt.Println(a == b, a.Cmp(b) == 0)
}
false true 0
false true
false true

Writing your own Equal method

When a struct contains slices or maps, or when equality has domain meaning (e.g. ignore a cache field, compare case-insensitively), write an Equal method:

package main

import (
	"fmt"
	"slices"
)

type Money struct {
	Cents    int64
	Currency string
}

type Order struct {
	ID    int
	Total Money
	Items []string
}

func (o Order) Equal(other Order) bool {
	return o.ID == other.ID &&
		o.Total == other.Total && // Money is comparable
		slices.Equal(o.Items, other.Items)
}

func main() {
	o1 := Order{1, Money{999, "USD"}, []string{"book"}}
	o2 := Order{1, Money{999, "USD"}, []string{"book"}}
	fmt.Println(o1.Equal(o2))
	o2.Items = append(o2.Items, "pen")
	fmt.Println(o1.Equal(o2))
}
true
false

The convention func (T) Equal(T) bool is recognized by go-cmp, which calls it automatically.

If you want to prevent anyone from using == on a struct, add a zero-size non-comparable field: _ [0]func(). It takes no space but makes the struct non-comparable, turning accidental comparisons into compile errors.

Ordering with cmp and slices

The cmp package provides generic helpers for ordered types, and the built-in min and max functions (Go 1.21+) work on any ordered type:

package main

import (
	"cmp"
	"fmt"
	"slices"
	"strings"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	fmt.Println(cmp.Compare(1, 2), cmp.Compare("b", "a"), cmp.Compare(3.5, 3.5))
	fmt.Println(cmp.Less(1, 2), min(3, 1, 2), max("apple", "pear"))

	people := []Person{
		{"Carol", 30},
		{"alice", 25},
		{"Bob", 30},
		{"Dave", 25},
	}

	// sort by age descending, then by name (case-insensitive)
	slices.SortFunc(people, func(a, b Person) int {
		return cmp.Or(
			cmp.Compare(b.Age, a.Age),
			strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name)),
		)
	})
	fmt.Println(people)

	i, found := slices.BinarySearchFunc(people, 25, func(p Person, age int) int {
		return cmp.Compare(age, p.Age)
	})
	fmt.Println(i, found)

	fmt.Println(slices.Compare([]int{1, 2, 3}, []int{1, 2, 4}), slices.Compare([]int{1, 2}, []int{1, 2, 0}))
}
-1 1 0
true 1 pear
[{Bob 30} {Carol 30} {alice 25} {Dave 25}]
2 true
-1 -1

Unlike <, cmp.Compare and cmp.Less define a total order for floats: NaN is less than every other value and equal to NaN. That makes them safe for sorting slices that may contain NaN.

Generic constraints: comparable and cmp.Ordered

When writing generic code, the constraint decides which operators you can use:

package main

import (
	"cmp"
	"fmt"
	"math"
)

func Index[T comparable](s []T, v T) int {
	for i, x := range s {
		if x == v {
			return i
		}
	}
	return -1
}

func Max[T cmp.Ordered](s []T) T {
	m := s[0]
	for _, x := range s[1:] {
		if x > m {
			m = x
		}
	}
	return m
}

type Key struct {
	Host string
	Port int
}

func main() {
	fmt.Println(Index([]string{"a", "b", "c"}, "c"))
	fmt.Println(Index([]Key{{"a", 80}, {"b", 443}}, Key{"b", 443}))
	fmt.Println(Max([]float64{1.5, -2, 9.25}))
	fmt.Println(Max([]string{"kiwi", "apple", "zucchini"}))

	nan := math.NaN()
	fmt.Println(cmp.Compare(nan, 1.0), cmp.Compare(nan, nan), nan < 1.0)

	// comparable accepts interface types since Go 1.20, may panic at runtime
	fmt.Println(Index([]any{1, "x"}, any("x")))
}
2
1
9.25
zucchini
-1 0 false
1

Since Go 1.20, interface types such as any satisfy comparable. That's convenient (you can have map[any]V in generic code), but as shown earlier, comparing interfaces holding slices, maps or functions panics at runtime.

There's no constraint for "has an Equal method" in the standard library. If you need one, define it yourself:

type Equaler[T any] interface {
	Equal(T) bool
}

func IndexFunc[T Equaler[T]](s []T, v T) int {
	return slices.IndexFunc(s, v.Equal)
}

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents