Golang bytes.Compare() Function with Examples

Golang | bytes.Compare() Function: Here, we are going to learn about the Compare() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 21, 2021

bytes.Compare()

The Compare() function is an inbuilt function of the bytes package which is used to compare two byte slices lexicographically and returns an integer value comparing two byte slices.

It accepts two parameters (a, b []byte) and returns 0 if a==b, -1 if a < b, and +1 if a > b.

Syntax:

func Compare(a, b []byte) int

Parameter(s):

  • a, b : Two byte slices to be compared.

Return Value:

The return type of the bytes.Compare() function is an int, it returns 0 if a==b, -1 if a < b, and +1 if a > b.

Example 1:

// Golang program to demonstrate the
// example of bytes.Compare() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Declaring byte slices
	var a = []byte{10, 20, 30, 70, 120, 255}
	var b = []byte{100, 120, 50, 70, 120, 255}
	var c = []byte{10, 20, 30, 70, 120, 255}

	// Comparing byte slices and printing results
	fmt.Println(bytes.Compare(a, b))
	fmt.Println(bytes.Compare(b, c))
	fmt.Println(bytes.Compare(a, c))
}

Output:

-1
1
0

Example 2:

// Golang program to demonstrate the
// example of bytes.Compare() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Declaring byte slices
	var a = []byte{10, 20, 30, 70, 120, 255}
	var b = []byte{100, 120, 50, 70, 120, 255}
	var c = []byte{10, 20, 30, 70, 120, 255}

	// Comparing byte slices and printing results
	result := bytes.Compare(a, b)
	if result == 0 {
		fmt.Printf("%d, both a and b are equal\n", result)
	} else if result < 0 {
		fmt.Printf("%d, a is less than b\n", result)
	} else {
		fmt.Printf("%d, a is greater than b\n", result)
	}

	result = bytes.Compare(b, c)
	if result == 0 {
		fmt.Printf("%d, both b and c are equal\n", result)
	} else if result < 0 {
		fmt.Printf("%d, b is less than c\n", result)
	} else {
		fmt.Printf("%d, b is greater than c\n", result)
	}

	result = bytes.Compare(a, c)
	if result == 0 {
		fmt.Printf("%d, both a and c are equal\n", result)
	} else if result < 0 {
		fmt.Printf("%d, a is less than c\n", result)
	} else {
		fmt.Printf("%d, a is greater than c\n", result)
	}
}

Output:

-1, a is less than b
1, b is greater than c
0, both a and c are equal

Golang bytes Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.