Cookies management by TermsFeed Cookie Consent

🙌 Case-insensitive string comparison in Go

introduction strings

Is there a case-insensitive string comparison function in Go? Of course! Although the name does not seem to indicate it, strings.EqualFold deals with it:

package main

import (
    "fmt"
    "strings"
)

func main() {
    foo1 := "foo"
    foo2 := "FOO"
    fmt.Println(strings.EqualFold(foo1, foo2))
}

You may ask now why we can’t convert both strings to upper or lowercase and, in this way, compare if they are case-insensitive equal. Of course, it works, but not for any case and any language. For example, in Greek, there are 3 forms of sigma letter:

g1 := "ς" // a final lowercase sigma
g2 := "Σ" // a capital sigma
g3 := "σ" // a non-final sigma

fmt.Println(strings.ToLower(g1))
fmt.Println(strings.ToLower(g2))
fmt.Println(strings.ToLower(g3))

fmt.Println(strings.EqualFold(g1, g2))
fmt.Println(strings.EqualFold(g1, g3))
fmt.Println(strings.EqualFold(g2, g3))

Output:

ς
σ
σ
true
true
true

Converting them to lowercase doesn’t give the same form, but a comparison using strings.EqualFold informs that they are equal. This is because strings.EqualFold uses case folding (now it’s clear why the function is named EqualFold) method which respects the case rules of different languages, so it always should be preffered method of case-insensitive comparison.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🍒 Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🔟 Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool