Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Operators

Go comparison operators

Reference for Go comparison operators: which types are comparable, ordered types, struct and array equality, interface comparison, NaN and the panic cases.

Comparison operators produce an untyped boolean. Equality (==, !=) works on comparable types; the ordering operators (<, <=, >, >=) work only on ordered types: integers, floats and strings.

Both operands must have identical types, or one must be assignable to the other's type, such as an untyped constant or a value compared with an interface it implements. Comparing mismatched types such as int and int64 does not compile.

Go
fmt.Println(3 < 5, "a" < "b", [2]int{1, 2} == [2]int{1, 2})

Try it

Go Comparing values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Interfaces and the run-time panic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
x == y   x != y
x <  y   x <= y   x >  y   x >= y
Type == / != < <= > >=
Integers, floats yes yes
Strings yes yes, byte-wise lexicographic
Booleans yes no
Pointers, channels yes (identity) no
Arrays, structs yes, if all elements or fields are comparable no
Interfaces yes; panics if dynamic types match and are not comparable no
Slices, maps, functions only against nil no

Usage notes

  • Floating point. Any comparison with NaN is false except !=. Equality on floats is exact; use a tolerance for computed values.
  • Strings compare by bytes, so "Z" < "a" is true and non-ASCII text is ordered by UTF-8 bytes, not by locale. For case-insensitive equality use strings.EqualFold; for ordering, use cmp.Compare or strings.Compare (three-way result).
  • Interface values are equal when their dynamic types are identical and the dynamic values are equal, or both are nil. A non-nil interface holding a nil pointer is not equal to nil.
  • Deep comparisons. For slices, use slices.Equal; for maps, maps.Equal; for arbitrary structures, reflect.DeepEqual (slow, with surprising nil-versus-empty behavior).
  • Struct equality compares fields in order and skips blank _ fields; a struct with a slice field is not comparable and cannot be a map key.
  • Errors. Compare with errors.Is rather than == when errors may be wrapped.
  • Chained comparisons like a < b < c are a compile error: the first result is a boolean. Write a < b && b < c.
  • Results are untyped booleans, so type Flag bool; var f Flag = 1 < 2 works.