0
0
GoHow-ToBeginner · 3 min read

How to Compare Strings in Go: Syntax and Examples

In Go, you compare strings using the == operator to check if they are equal or != to check if they are different. For ordering comparisons, use <, >, <=, and >= operators directly on strings.
📐

Syntax

In Go, you can compare strings using comparison operators:

  • ==: checks if two strings are exactly equal.
  • !=: checks if two strings are not equal.
  • <, >, <=, >=: compare strings lexicographically (dictionary order).

These operators return a boolean value (true or false).

go
str1 == str2
str1 != str2
str1 < str2
str1 > str2
str1 <= str2
str1 >= str2
💻

Example

This example shows how to compare two strings for equality and order, printing the results.

go
package main

import (
	"fmt"
)

func main() {
	str1 := "apple"
	str2 := "banana"

	fmt.Println("str1 == str2:", str1 == str2)   // false
	fmt.Println("str1 != str2:", str1 != str2)   // true
	fmt.Println("str1 < str2:", str1 < str2)     // true
	fmt.Println("str1 > str2:", str1 > str2)     // false
	fmt.Println("str1 <= str2:", str1 <= str2)   // true
	fmt.Println("str1 >= str2:", str1 >= str2)   // false
}
Output
str1 == str2: false str1 != str2: true str1 < str2: true str1 > str2: false str1 <= str2: true str1 >= str2: false
⚠️

Common Pitfalls

One common mistake is trying to compare strings using functions like strings.Compare without understanding its return value. strings.Compare returns an integer: 0 if equal, -1 if first is less, and 1 if first is greater. Using == and other operators is simpler and clearer for most cases.

Also, avoid comparing strings with == if you want case-insensitive comparison; use strings.EqualFold instead.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	str1 := "GoLang"
	str2 := "golang"

	// Wrong: case-sensitive equality
	fmt.Println("str1 == str2:", str1 == str2) // false

	// Right: case-insensitive equality
	fmt.Println("strings.EqualFold(str1, str2):", strings.EqualFold(str1, str2)) // true
}
Output
str1 == str2: false strings.EqualFold(str1, str2): true
📊

Quick Reference

Here is a quick summary of string comparison operators in Go:

OperatorMeaningExample Result
==Checks if two strings are equal"a" == "a" → true
!=Checks if two strings are not equal"a" != "b" → true
<Checks if first string is lexicographically less"apple" < "banana" → true
>Checks if first string is lexicographically greater"banana" > "apple" → true
<=Checks if first string is less or equal"apple" <= "apple" → true
>=Checks if first string is greater or equal"banana" >= "apple" → true

Key Takeaways

Use == and != operators to check if strings are equal or not in Go.
Use <, >, <=, >= to compare strings lexicographically (dictionary order).
For case-insensitive comparison, use strings.EqualFold instead of ==.
Avoid using strings.Compare unless you need the integer comparison result.
String comparison operators return boolean values directly.