0
0
GoHow-ToBeginner · 3 min read

How to Use Comparison Operators in Go: Syntax and Examples

In Go, you use ==, !=, <, <=, >, and >= to compare values. These operators return a boolean true or false depending on the comparison result.
📐

Syntax

Comparison operators in Go compare two values and return a boolean result. Here are the operators:

  • ==: equal to
  • !=: not equal to
  • <: less than
  • <=: less than or equal to
  • >: greater than
  • >=: greater than or equal to

They work with numbers, strings, and other comparable types.

go
value1 == value2
value1 != value2
value1 < value2
value1 <= value2
value1 > value2
value1 >= value2
💻

Example

This example shows how to use comparison operators with integers and strings. It prints the result of each comparison.

go
package main

import "fmt"

func main() {
    a := 5
    b := 10
    fmt.Println("a == b:", a == b)   // false
    fmt.Println("a != b:", a != b)   // true
    fmt.Println("a < b:", a < b)     // true
    fmt.Println("a <= b:", a <= b)   // true
    fmt.Println("a > b:", a > b)     // false
    fmt.Println("a >= b:", a >= b)   // false

    s1 := "apple"
    s2 := "banana"
    fmt.Println("s1 == s2:", s1 == s2) // false
    fmt.Println("s1 != s2:", s1 != s2) // true
    fmt.Println("s1 < s2:", s1 < s2)   // true (lexicographic)
}
Output
a == b: false a != b: true a < b: true a <= b: true a > b: false a >= b: false s1 == s2: false s1 != s2: true s1 < s2: true
⚠️

Common Pitfalls

Common mistakes include:

  • Using = instead of == for comparison (this is assignment, not comparison).
  • Comparing incompatible types (e.g., int and string) causes a compile error.
  • Assuming string comparison is case-insensitive (it is case-sensitive).
go
package main

import "fmt"

func main() {
    a := 5
    b := 10

    // Wrong: assignment instead of comparison
    // if a = b { // compile error: cannot use assignment in if condition
    //     fmt.Println("Equal")
    // }

    // Correct:
    if a == b {
        fmt.Println("Equal")
    } else {
        fmt.Println("Not equal")
    }

    // Wrong: comparing different types
    // if a == "5" { // compile error: mismatched types int and string
    //     fmt.Println("Equal")
    // }
}
Output
Not equal
📊

Quick Reference

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
<Less than3 < 5true
<=Less than or equal to5 <= 5true
>Greater than7 > 5true
>=Greater than or equal to5 >= 5true

Key Takeaways

Use == and != to check if values are equal or not equal.
Use <, <=, >, >= to compare order between values.
Comparison operators return true or false.
Do not confuse = (assignment) with == (comparison).
Only compare values of compatible types.