Sobes.tech
Senior

Can a slice be compared using double equals (==)?

sobes.tech AI

Answer from AI

In Go, slices cannot be compared 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.

Example:

var a, b []int
fmt.Println(a == nil) // true
fmt.Println(b == nil) // true
// fmt.Println(a == b) // compile error: invalid operation: a == b (slice can only be compared to nil)

To compare the contents of two slices, you need to do it manually, for example, using a loop or with a function from the reflect package:

import "reflect"

func slicesEqual(a, b []int) bool {
    return reflect.DeepEqual(a, b)
}

Or write your own element comparison function.

Can a slice be compared using double equals (==)… - sobes.tech