← All languages
Go function of the day
Random

bytes.Equal

Report whether two byte slices are of the same length and contain the same bytes.

Description

The bytes.Equal function reports whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice, so bytes.Equal(nil, []byte{}) returns true.

The comparison is performed in constant time relative to the data being compared (length is still checked first), but it is NOT cryptographically constant-time. For comparing secrets such as MAC tags or password hashes, use crypto/subtle.ConstantTimeCompare to avoid timing side-channel leaks.

bytes.Equal is the canonical way to compare two []byte values; the == operator does not work on slices. Most modern Go implementations use highly optimized SIMD code to make the comparison nearly free for cache-resident data.

Arguments

NameDescriptionOptional
a First byte slice. No
b Second byte slice. No

Example

import "bytes"

bytes.Equal([]byte("foo"), []byte("foo")) // true
bytes.Equal([]byte("foo"), []byte("bar")) // false
bytes.Equal(nil, []byte{})                // true

Reference