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.
fmt.Println(3 < 5, "a" < "b", [2]int{1, 2} == [2]int{1, 2})
Try it
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.
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
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
NaNis 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 usestrings.EqualFold; for ordering, usecmp.Compareorstrings.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.Israther than==when errors may be wrapped. - Chained comparisons like
a < b < care a compile error: the first result is a boolean. Writea < b && b < c. - Results are untyped booleans, so
type Flag bool; var f Flag = 1 < 2works.