Home
Go
String Equal and EqualFold
Updated Mar 18, 2025
Dot Net Perls
String equals. Go strings may have the same rune content, and this is important for us to detect. The strings may have been created in different ways.
In Go we use the equality operator to test the contents of strings. This is case-sensitive. Strings.EqualFold can be used for case insensitivity.
String equals example. Here we create 2 strings that end up having the same values ("catcat"). They are not the same string, but their contents are identical.
Info We use the double-equals sign operator to test the strings. This evaluates to true, so the "Strings are equal" message is printed.
package main import ( "fmt" "strings" ) func main() { // Create 2 equal strings in different ways. test1 := "catcat" test2 := strings.Repeat("cat", 2) // Display the strings. fmt.Println("test1:", test1) fmt.Println("test2:", test2) // Test the strings for equality. if test1 == test2 { fmt.Println("Strings are equal") } if test1 != test2 { fmt.Println("Not reached") } }
test1: catcat test2: catcat Strings are equal
EqualFold. Uppercase letters are not equal to lowercase letters. But with EqualFold we fold cases. This makes "A" equal to "a." No string copies or conversions are required.
Tip Using EqualFold instead of creating many strings by lowercasing them can optimize performance.
package main import ( "fmt" "strings" ) func main() { value1 := "cat" value2 := "CAT" // This returns true because cases are ignored. if strings.EqualFold(value1, value2) { fmt.Println(true) } }
true
With the equals-sign operator and strings.EqualFold, we can compare strings. Case-insensitivity is not always needed. Using the equals operator is best when it is sufficient.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 18, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen