The bytes.Compare() Function in Golang compares two-byte slices lexicographically and returns an integer value indicating the comparison result. It accepts two parameters, a and b, of type []byte and returns 0 if a==b, -1 if a < b, and +1 if a > b.
Syntax
func Compare(a, b []byte) int
Parameters
The function accepts two arguments, a and b, both byte slices
Return value
The function returns:
- -1 if a is lexicographically smaller than b
- 0 if a is lexicographically equal to b
- 1 if a is lexicographically greater than b
Example
package main
import (
"bytes"
"fmt"
)
func main() {
a := []byte("apple")
b := []byte("mango")
result := bytes.Compare(a, b)
switch result {
case -1:
fmt.Println("a is less than b")
case 0:
fmt.Println("a is equal to b")
case 1:
fmt.Println("a is greater than b")
}
}
Output
a is less than b
In this example, the output will be “a is less than b” because “apple” is lexicographically smaller than “mango”.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.