Explains Go comparison operators, their meanings, type comparability rules, and examples for equality and ordering operations.
Comparison operators compare two operands and return a Boolean value: true or false. Equality operators (==, !=) require operands to be of comparable types (typically the same type or types that the language allows to be compared). Ordering operators (<, <=, >, >=) require ordered types such as numeric types and strings. Common comparisons include checking whether two strings match, if two numbers are equal, or if one number is greater than another.
Not all types are comparable using == and !=. Types such as slices, maps, and functions cannot be compared with equality operators — attempting to do so results in a compile-time error. Structs and arrays are comparable only if all their fields/elements are comparable.
We have the following comparison operators: equal (==), not equal (!=), less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=).
When comparing values in Go, make sure both operands are of comparable types. Use explicit conversions when necessary (for example, converting between int types) and prefer clear, readable comparisons to avoid subtle bugs.
Operator reference
Operator
Meaning
Typical Use Case
==
equal
Compare identical values or strings
!=
not equal
Check inequality
<
less than
Order comparisons (numbers, strings)
<=
less than or equal to
Order or boundary checks
>
greater than
Order comparisons
>=
greater than or equal to
Order or boundary checks
ExamplesEqual (==)
The equal operator returns true when the two values are equal.
Copy
package mainimport "fmt"func main() { var city string = "Kolkata" var city2 string = "Calcutta" fmt.Println(city == city2)}
Copy
$ go run main.gofalse
Not equal (!=)
The not-equal operator returns true when the two values are not equal.
Copy
package mainimport "fmt"func main() { var city string = "Kolkata" var city2 string = "Calcutta" fmt.Println(city != city2)}
Copy
$ go run main.gotrue
Less than (<)
The less-than operator returns true when the left operand is strictly less than the right operand.
Copy
package mainimport "fmt"func main() { var a, b int = 5, 10 fmt.Println(a < b)}
Copy
$ go run main.gotrue
Less than or equal to (<=)
This operator returns true when the left operand is less than or equal to the right operand.
Copy
package mainimport "fmt"func main() { var a, b int = 10, 10 fmt.Println(a <= b)}
Copy
$ go run main.gotrue
Greater than (>)
The greater-than operator returns true when the left operand is strictly greater than the right operand.
Copy
package mainimport "fmt"func main() { var a, b int = 20, 10 fmt.Println(a > b)}
Copy
$ go run main.gotrue
Greater than or equal to (>=)
This operator returns true when the left operand is greater than or equal to the right operand.
Copy
package mainimport "fmt"func main() { var a, b int = 20, 20 fmt.Println(a >= b)}