Equality and comparison
suggest changeGo has two kinds of comparison operators:
- equality operators
==and!=work on comparable types - ordering operators
<,<=,>and>=work on ordered types: integers, floats and strings
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:
p1 == p2compares the struct values field by field and istrue.&p1 == &p2compares pointers: they point to different variables, so it'sfalse.- Comparable types are exactly the types you can use as map keys. A struct like
Pointis a natural, allocation-free composite key. - Both operands must have the same type (or one must be assignable to the other).
int(1) == int64(1)doesn't compile. Untyped constants like3.0are converted to the other operand's type.
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
slices.Equalchecks length and then compares elements with==. It treats anilslice and an empty slice as equal.slices.EqualFuncandmaps.EqualFunctake a custom function for elements, which also lets you compare slices of non-comparable types (e.g.[][]int) or of different types.bytes.Equalis the traditional way to compare[]byte. It's equivalent toslices.Equalfor bytes.maps.Equalchecks that both maps have the same keys with equal values. Order doesn't matter (maps have no order).
reflect.DeepEqual
reflect.DeepEqual recursively compares any two values, including structs that contain slices and maps. It's convenient but has drawbacks:
- it uses reflection, so it's much slower than direct comparison
- it isn't type safe:
reflect.DeepEqual(1, int64(1))compiles and returnsfalse - a
nilslice is not deep-equal to an empty slice, which often surprises people in tests - it compares unexported fields, and functions are only equal if both are
nil
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
- Results of float arithmetic are rounded, so compare computed values with a tolerance, not
==. The relative tolerance inalmostEqualscales with the size of the numbers. Near zero you may want an absolute tolerance instead. 0.1+0.2 == 0.3istruewhen written with constants because Go evaluates untyped constant expressions with arbitrary precision.NaNis not equal to anything, including itself. Usemath.IsNaN.-0.0 == 0.0istrue.- A
NaNmap key can be inserted but never looked up or overwritten. Each insert adds a new entry.clear(m)removes them.
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
time.Timestores a location and an optional monotonic clock reading. Two values representing the same instant can differ in those fields, so==returnsfalse. Always useEqual,Before,AfterorCompare. This also meanstime.Timeis a poor map key, unless you normalize it first, e.g. witht.UTC().Round(0). See Compare time and date.*big.Intis a pointer, so==compares addresses. UseCmp, which returns -1, 0 or +1.
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
cmp.Compare(a, b)returns -1 ifa < b, 0 if equal and +1 ifa > b. This "three-way" result is whatslices.SortFunc,slices.BinarySearchFuncandslices.MaxFuncexpect.cmp.Orreturns its first non-zero argument, which makes multi-key comparisons a one-liner: if ages differ, that result wins; otherwise names decide.- To reverse an order, swap the arguments:
cmp.Compare(b.Age, a.Age). slices.Comparecompares slices lexicographically. A shorter slice that is a prefix of a longer one sorts first.- The comparison function given to
slices.BinarySearchFuncmust match the order the slice is sorted in. Here the slice is sorted by descending age, so the arguments are swapped compared to the usualcmp.Compare(p.Age, age).
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:
comparableallows==and!=cmp.Orderedallows<,<=,>,>=(and==); it covers integers, floats and strings, including named types liketype Celsius float64
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
==works on basic types, pointers, channels, interfaces, and arrays and structs made of comparable types- slices, maps and functions only compare to
nil; useslices.Equal,maps.Equal,bytes.Equalorreflect.DeepEqual - comparing interfaces whose dynamic type isn't comparable panics at runtime
- an interface holding a
nilpointer is notnil - compare computed floats with a tolerance;
NaN != NaN - use
Equal/Compare/Cmpmethods fortime.Timeandmath/big - use
errors.Isinstead of==for errors - use
cmp.Compare,cmp.Orandslices.SortFuncfor ordering,comparableandcmp.Orderedin generic code