In Go, a slice is a powerful, flexible data structure that allows elements of the same type to be stored in a variable-length sequence. When working with byte slices ([]byte), Go provides easy-to-use functions in the bytes package to compare them. In this article we will learn "How to compare two slices of bytes in Golang".
Example
slice1 := []byte{'G', 'o', 'l', 'a', 'n', 'g'}
slice2 := []byte{'G', 'o', 'l', 'a', 'n', 'g'}
slice3 := []byte{'g', 'o', 'L', 'A', 'N', 'g'}Syntax
func Compare(a, b []byte) int #bytes.Compare() func Equal(a, b []byte) bool #bytes.Equal() func DeepEqual(x, y interface{}) bool #reflect.DeepEqual()
Table of Content
Comparing with bytes.Compare()
The bytes.Compare function returns:
0if the slices are equal,-1ifslice1is less thanslice2, and1ifslice1is greater thanslice2.
Syntax
func Compare(a, b []byte) int
Example:
package main
import (
"bytes"
"fmt"
)
func main() {
slice1 := []byte{'G', 'o', 'l', 'a', 'n', 'g'}
slice2 := []byte{'G', 'o', 'l', 'a', 'n', 'g'}
slice3 := []byte{'g', 'o', 'L', 'A', 'N', 'g'}
fmt.Println(bytes.Compare(slice1, slice2)) // Output: 0 (equal)
fmt.Println(bytes.Compare(slice1, slice3)) // Output: -1 (slice1 < slice3)
}
Output
0 -1
Comparing with bytes.Equal()
To directly check if two byte slices are equal, use bytes.Equal, which returns true if the slices are identical.
Syntax
func Equal(a, b []byte) boolExample
package main
import (
"bytes"
"fmt"
)
func main() {
slc1 := []byte{'G', 'o', 'l', 'a', 'n', 'g'}
slc2 := []byte{'G', 'o', 'l', 'a', 'n', 'g'}
slc3 := []byte{'g', 'o', 'L', 'A', 'N', 'g'}
fmt.Println(bytes.Equal(slc1, slc2)) // Output: true
fmt.Println(bytes.Equal(slc1, slc3)) // Output: false
}
Output
true false
Using reflect.DeepEqual() (Alternative Method)
reflect.DeepEqual compares the values and structure of two variables. While not specific to byte slices, it can also be used for equality checks.
Syntax
func DeepEqual(x, y interface{}) boolExample
package main
import (
"fmt"
"reflect"
)
func main() {
slc1 := []byte{'G', 'o', 'l', 'a', 'n', 'g'}
slc2 := []byte{'G', 'o', 'l', 'a', 'n', 'g'}
slc3 := []byte{'g', 'o', 'L', 'A', 'N', 'g'}
fmt.Println(reflect.DeepEqual(slc1, slc2)) // Output: true
fmt.Println(reflect.DeepEqual(slc1, slc3)) // Output: false
}
Output
true false