How to Compare Strings in Go (Case-Sensitive and Insensitive)

Use the built-in `==` operator for case-sensitive comparisons and the `strings.EqualFold` function for case-insensitive checks.

Use the built-in == operator for case-sensitive comparisons and the strings.EqualFold function for case-insensitive checks. Go does not have a built-in case-insensitive operator, so you must explicitly call the helper function from the strings package when order or casing shouldn't matter.

For case-sensitive logic, the standard equality operator works exactly as expected, returning true only if the byte sequences match perfectly. For case-insensitive scenarios, strings.EqualFold handles Unicode case folding correctly, which is superior to manually converting both strings to lowercase using strings.ToLower, especially when dealing with non-ASCII characters like Turkish "İ" or German "ß".

Here is a practical example demonstrating both approaches:

package main

import (
	"fmt"
	"strings"
)

func main() {
	s1 := "GoLang"
	s2 := "golang"

	// Case-sensitive comparison
	if s1 == s2 {
		fmt.Println("Match (Case-Sensitive)")
	} else {
		fmt.Println("No Match (Case-Sensitive)")
	}

	// Case-insensitive comparison
	if strings.EqualFold(s1, s2) {
		fmt.Println("Match (Case-Insensitive)")
	} else {
		fmt.Println("No Match (Case-Insensitive)")
	}
}

When comparing strings in production code, avoid manual ToLower conversions unless you specifically need the transformed string for storage or display. strings.EqualFold is optimized for comparison and handles edge cases in Unicode normalization that simple lowercasing might miss. If you are working with byte slices instead of strings, you can use bytes.Equal for case-sensitive checks and bytes.EqualFold for case-insensitive ones.

Output:

No Match (Case-Sensitive)
Match (Case-Insensitive)

Remember that strings.EqualFold is generally preferred over strings.ToLower for comparisons because it avoids the allocation of new strings required by ToLower, making it more performant in tight loops or high-throughput services.