Sobes.tech
Senior

Can two slices be compared directly (a == b)?

sobes.tech AI

Answer from AI

In Go, you cannot compare two slices directly using the == operator, except when comparing with nil. This is because a slice is a structure containing a pointer to an array, a length, and a capacity, and the == operator is not defined for comparing the contents of slices.

To compare two slices by their contents, you need to compare their elements element by element. For example:

func equalSlices(a, b []int) bool {
    if len(a) != len(b) {
        return false
    }
    for i := range a {
        if a[i] != b[i] {
            return false
        }
    }
    return true
}

For byte slices, you can use bytes.Equal from the standard library.