What is bytes.Compare() Function in Golang

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. -1 if a is lexicographically smaller than b
  2. 0 if a is lexicographically equal to b
  3. 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.