Home »
Golang »
Golang Reference
Golang bytes.Equal() Function with Examples
Golang | bytes.Equal() Function: Here, we are going to learn about the Equal() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 22, 2021
bytes.Equal()
The Equal() function is an inbuilt function of the bytes package which is used to check whether both byte slices a and b are the same length and contain the same bytes.
It accepts two parameters (a, b []byte) and returns true if a and b are the same length and contain the same bytes; false, otherwise.
Syntax
func Equal(a, b []byte) bool
Parameters
- a, b : The byte slices to be checked.
Return Value
The return type of the bytes.Equal() function is a bool, it returns true if a and b are the same length and contain the same bytes; false, otherwise.
Example 1
// Golang program to demonstrate the
// example of bytes.Equal() 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.Equal(a, b))
fmt.Println(bytes.Equal(b, c))
fmt.Println(bytes.Equal(a, c))
}
Output:
false
false
true
Example 2
// Golang program to demonstrate the
// example of bytes.Equal() 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.Equal(a, b)
if result == true {
fmt.Printf("%t, both a and b are equal\n", result)
} else {
fmt.Printf("%t, both a and b are not equal\n", result)
}
result = bytes.Equal(b, c)
if result == true {
fmt.Printf("%t, both b and c are equal\n", result)
} else {
fmt.Printf("%t, both b and c are not equal\n", result)
}
result = bytes.Equal(a, c)
if result == true {
fmt.Printf("%t, both a and c are equal\n", result)
} else {
fmt.Printf("%t, both a and c are not equal\n", result)
}
}
Output:
false, both a and b are not equal
false, both b and c are not equal
true, both a and c are equal
Example 3:
// Golang program to demonstrate the
// example of bytes.Equal() function
package main
import (
"bytes"
"fmt"
)
func main() {
// Comparing strings
var a string
var b string
a = "Hello, world!"
b = "Hello, world!"
if bytes.Equal([]byte(a), []byte(b)) == true {
fmt.Printf("%q and %q are equal\n", a, b)
} else {
fmt.Printf("%q and %q are not equal\n", a, b)
}
a = "Hello, world!"
b = "Hello, WORLD!"
if bytes.Equal([]byte(a), []byte(b)) == true {
fmt.Printf("%q and %q are equal\n", a, b)
} else {
fmt.Printf("%q and %q are not equal\n", a, b)
}
}
Output:
"Hello, world!" and "Hello, world!" are equal
"Hello, world!" and "Hello, WORLD!" are not equal
Golang bytes Package »