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 the string type and is the first of the two input strings to be compared.

  • b: this argument is of the string type 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):

  • 0 is returned when the first string equals the second string (a==b).
  • +1 is returned when the first string is Lexicographically greater than the second string (a>b).
  • -1 is returned when the first string is Lexicographically smaller than the second string (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 main
import (
"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)
}
Example: Compare function

It is usually clearer and always faster to use the built-in string comparison operators ==, <, >, than the Compare function.

Free Resources

Attributions:
  1. undefined by undefined