What is the Compare function in Golang?
The Compare function, as the name suggests, compares two strings using Lexicographic ordering and tells us which of them is greater or equal.
In Mathematics, the Lexicographic order is a generalization of the alphabetical order used in dictionaries.
To use this function, you must import the strings package in your file and access the Compare function within it using the . notation (string.Compare). Here, Compare is the actual function, while string is the Go package that stores the definition of this function.
Function definiton
The definition of the Compare function inside the string package is shown below:
Parameters
The Compare function takes two arguments:
-
a: this argument is of thestringtype and is the first of the two input strings to be compared. -
b: this argument is of thestringtype and is the second of the two input strings to be compared.
Return value
The Compare function can return three values (all of them type int):
0is returned when the first string equals the secondstring(a==b).+1is returned when the first string is Lexicographically greater than the secondstring(a>b).-1is returned when the first string is Lexicographically smaller than the secondstring(a<b).
Code
Below is a simple example where we show the Compare function used in three different input scenarios to produce three different outputs:
package mainimport ("fmt""strings")func main() {greater:= strings.Compare("Z", "A")equal := strings.Compare("W", "W")lesser:= strings.Compare("A", "Z")fmt.Println(greater)fmt.Println(equal)fmt.Println(lesser)}
It is usually clearer and always faster to use the built-in string comparison operators
==,<,>, than theComparefunction.
Free Resources
- undefined by undefined