Go – Check if Strings are Equal
To check if strings are equal in Go programming, use equal to operator ==
and provide the two strings as operands to this operator. If both the strings are equal, equal to operator returns true, otherwise the operator returns false.
We can also use strings.Compare(string, string)
function to check if the strings are equal. If the two strings are equal, then strings.Compare() function returns an integer value of 0
. We may use this as a condition to check if strings are equal.
Please note that using Equal to Operator is better than compared to strings.Compare() in terms of performance.
In this tutorial, we go through examples for each of the above methods.
Examples
In the following program, we take two string values in str1
and str2
. We check if these two strings are equal using equal to operator.
example.go
package main
import "fmt"
func main() {
str1 := "Abc"
str2 := "Abc"
result := str1 == str2
fmt.Println("Are the two strings equal: ", result)
}
Output
Are the two strings equal: true
Since equal to operator returns a boolean value, we can use the expression str1 == str2 as a condition for if statement.
example.go
package main
import "fmt"
func main() {
str1 := "Abc"
str2 := "Abc"
if str1 == str2 {
fmt.Println("The two strings are equal.")
} else {
fmt.Println("The two strings are not equal.")
}
}
Output
The two strings are equal.
Now, let us use strings.Compare(string, string) function, to check if strings are equal.
example.go
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "Abc"
str2 := "Abc"
if strings.Compare(str1, str2) == 0 {
fmt.Println("The two strings are equal.")
} else {
fmt.Println("The two strings are not equal.")
}
}
Output
The two strings are equal.
Conclusion
In this Golang Tutorial, we learned how to check if two strings are equal, with the help of example programs.