3 ways to compare slices/arrays

yourbasic.org/golang

Basic case

In most cases, you will want to write your own code to compare slices and arrays.

// Equal tells whether a and b contain the same elements.
// A nil argument is equivalent to an empty slice.
func Equal(a, b []int) bool {
    if len(a) != len(b) {
        return false
    }
    for i, v := range a {
        if v != b[i] {
            return false
        }
    }
    return true
}

Optimzed code for byte slices

To compare byte slices, use the optimized bytes.Equal. This function also treats nil arguments as equivalent to empty slices.

General-purpose code for recursive comparison

For testing purposes, you may want to use reflect.DeepEqual. It compares two elements of any type recursively.

var a []int = nil
var b []int = make([]int, 0)
fmt.Println(reflect.DeepEqual(a, b)) // false

The performance of this function is much worse than for the code above, but it’s useful in test cases where simplicity and correctness are crucial. The semantics, however, are quite complicated.

Further reading

Slices and arrays in a nutshell

Share this page: