Golang bytes.Compare() function is “used to compare 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 seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.