C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Equals: We use the double-equals sign operator to test the strings. This evaluates to true, so the "Strings are equal" message is printed.
Golang program that tests for equal strings
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")
}
}
Output
test1: catcat
test2: catcat
Strings are equal
Tip: Using EqualFold instead of creating many strings by lowercasing them can optimize performance.
Golang program that uses EqualFold
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)
}
}
Output
true