Menu Close

Go – bytes.Equal() function in go

bytes.Equal() function is used to check whether two byte slices are same length and contain the same bytes in go.

Equal() built-in function of bytes package or bytes.Equal() function takes two byte slices as arguments and check whether they are equal or not by comparing them.

bytes.Equal() function prototype:

func Equal(a, b []byte) bool

or

func Equal(a []byte, b []byte) bool

Input parameters:
a: byte slice
b: byte slice

Return:
It returns true if both the byte slices are equal else false.

Explanation:

1)
a := []byte("abcd")
b := []byte("abcd")

Output: true, since both the byte slices are equal.

2)
a := []byte("abcd")
b := []byte("xyza")

Output: false, since both the byte slices are not equal.

3)
a := []byte{10, 20, 30}
b := []byte{10, 20, 30}

Output: true, since both the byte slices are equal.

4)
a := []byte("去是伟大的!")
b := []byte("去是伟大的!")

Output: true, since both the byte slices are equal.

Example:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    // Both the byte slices are equal
    a := []byte("abcd")
    b := []byte("abcd")

	fmt.Println(bytes.Equal(a, b))
	
	
	// Both the byte slices are not equal
    a = []byte("abcd")
    b = []byte("xyza")
    
    fmt.Println(bytes.Equal(a, b))
	
	// Both the byte slices are equal
    a = []byte{10, 20, 30}
    b = []byte{10, 20, 30}

	fmt.Println(bytes.Equal(a, b))
	

	// Both the byte slices are equal
	a = []byte("去是伟大的!")
    b = []byte("去是伟大的!")
	
	fmt.Println(bytes.Equal(a, b))
}

Output:

true
false
true
true

*** Apart from Equal() function, you can also compare two byte slices using string typecast like string(a) == string(b). Here, a and b are two byte slices.

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *