Golang bytes.Equal() function is “used to check whether both byte slices a and b are the same length and contain the same bytes.”
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, and it returns true if a and b are the same length and contain the same bytes; false, otherwise.
Example 1: Comparing Byte Slices from Strings
package main
import (
"bytes"
"fmt"
)
func main() {
a := []byte("Golang")
b := []byte("Golang")
c := []byte("Python")
if bytes.Equal(a, b) {
fmt.Println("a and b are equal!")
} else {
fmt.Println("a and b are not equal!")
}
if bytes.Equal(a, c) {
fmt.Println("a and c are equal!")
} else {
fmt.Println("a and c are not equal!")
}
}
Output
a and b are equal!
a and c are not equal!
Example 2: Comparing Byte Slices from Files (Assuming two binary files, file1.bin and file2.bin)
package main
import (
"bytes"
"fmt"
"log"
"os"
)
func main() {
file1, err := os.ReadFile("file1.bin")
if err != nil {
log.Fatalf("Failed reading file1: %s", err)
}
file2, err := os.ReadFile("file2.bin")
if err != nil {
log.Fatalf("Failed reading file2: %s", err)
}
if bytes.Equal(file1, file2) {
fmt.Println("The contents of file1 and file2 are equal!")
} else {
fmt.Println("The contents of file1 and file2 are not equal!")
}
}
Output
fmt.Println("The contents of file1 and file2 are equal!")
Example 3: Simple program
package main
import (
"bytes"
"fmt"
)
func main() {
a := []byte("hello")
b := []byte("hello")
c := []byte("world")
fmt.Println(bytes.Equal(a, b))
fmt.Println(bytes.Equal(a, c))
}
Output
true
false
That’s it!
Related posts

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.