Checking the equality of two slices

slice can only be compared to nil
golang check if two slices have same elements
golang sort slice
golang find difference between two slices
golang slice
golang compare two string slices
golang compare two slices of structs
golang compare slices of structs

How can I check if two slices are equal?

You need to loop over each of the elements in the slice and test. Equality for slices is not defined. However, there is a bytes.Equal function if you are comparing values of type []byte.

func testEq(a, b []Type) bool {

    // If one is nil, the other must also be nil.
    if (a == nil) != (b == nil) { 
        return false; 
    }

    if len(a) != len(b) {
        return false
    }

    for i := range a {
        if a[i] != b[i] {
            return false
        }
    }

    return true
}

3 ways to compare slices (arrays) � YourBasic Go, In the Go slice, you are allowed to compare two slices of the byte type with each other using Compare() function. This function returns an� Answer You need to loop over each of the elements in the slice and test. Equality for slices is not defined. However, there is a bytes.Equal function if you are comparing values of type []byte.

You should use reflect.DeepEqual()

DeepEqual is a recursive relaxation of Go's == operator.

DeepEqual reports whether x and y are "deeply equal," defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

Array values are deeply equal when their corresponding elements are deeply equal.

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

Func values are deeply equal if both are nil; otherwise they are not deeply equal.

Interface values are deeply equal if they hold deeply equal concrete values.

Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.

Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

How to compare two slices of bytes in Golang?, In the Go slice of byes, you are allowed to check the equality of the slices with the help of Equal() function. This function returns true if both the� In the Go slice of byes, you are allowed to check the equality of the slices with the help of Equal () function. This function returns true if both the slices are equal, or return false if both the slices are not equal. It is defined under the bytes package so, you have to import bytes package in your program for accessing Equals function.

This is just example using reflect.DeepEqual() that is given in @VictorDeryagin's answer.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := []int {4,5,6}
    b := []int {4,5,6}
    c := []int {4,5,6,7}

    fmt.Println(reflect.DeepEqual(a, b))
    fmt.Println(reflect.DeepEqual(a, c))

}

Result:

true
false

Try it in Go Playground

How to check equality of slices of bytes in Golang?, We could use the hashing function to generate a key and compare the key to check for equality. Its like, generating check-sum for a slice and comparing the� They have implemented a custom HashMap data structure, which could take []byte (byte slice) as a key. We could use the hashing function to generate a key and compare the key to check for equality. Its like, generating check-sum for a slice and comparing the check-sum for equality check.

If you have two []byte, compare them using bytes.Equal. The Golang documentation says:

Equal returns a boolean reporting whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.

Usage:

package main

import (
    "fmt"
    "bytes"
)

func main() {
    a := []byte {1,2,3}
    b := []byte {1,2,3}
    c := []byte {1,2,2}

    fmt.Println(bytes.Equal(a, b))
    fmt.Println(bytes.Equal(a, c))
}

This will print

true
false

What's the best way to check the equality of two slices in Go?, Golang bytes Compare() is an inbuilt function that returns an integer comparing two-byte slices lexicographically. The final result will be 0 if� In most cases, you will want to write your own code to compare the elements of two slices. // 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 }

And for now, here is https://github.com/google/go-cmp which

is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal.

package main

import (
    "fmt"

    "github.com/google/go-cmp/cmp"
)

func main() {
    a := []byte{1, 2, 3}
    b := []byte{1, 2, 3}

    fmt.Println(cmp.Equal(a, b)) // true
}

How To Compare Two Slices In Golang With Example, How to compare slices (arrays) in Go. 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� We have existing solution for this problem please refer C Program to check if two given matrices are identical link. In python any iterable object is comparable so we can solve this problem quickly in python with the help of List Equality .

Go: Compare slices (arrays), How to compare equality of struct, slice and map? DeepEqual function from reflect package used to check x and y are “deeply equal”. This applies for : Array � This article deals with the task of ways to check if two unordered list contains exact similar elements in exact similar position, i.e to check if two lists are exactly equal. This is quite a useful utility and can be used in day-day programming. Method 1 : Using list.sort () and == operator sort () coupled with == operator can achieve this task.

How to compare equality of struct, slice and map in Golang, 3 ways to compare slices (arrays) � YourBasic Go, CODE EXAMPLE You reflect : DeepEqual returns false for equal slice with two elements in , The slices are� Two Slices. 1.9K likes. Catering, custom cake & cookie designs. By appointment only. Delicious sandwiches made with bread baked in house, salads topped with fresh ingredients, soups to warm the

check for equality on slices without order, Basically I have two slices of a certain type, which can be of random order and I want to be able to compare, that any of the data of one slice� On 5.10.0 that does indeed check that the arrays are equal. – hobbs Oct 22 '09 at 19:59. 6. For checking equality of two arrays try this. In given code, if %eq

Comments
  • The question really is about a simple task, but IMO it is a real question, with a very specific answer. How it could have been closed as "not a real question" by, as far as I can see, people I cannot recall being ever active in the Go tagged questions, is beyond me. Specifically: the question is non ambiguous, complete, narrow to a single (though simple) problem, non rhetorical and can be answered precisely and accurately in its current form. The == operator is defined in Go for only some types, so moreover, this question is also a legitimate one.
  • Still, it isn't any of the things mentioned in the close reason ("cannot reasonably be answered in its current form").
  • Hahaha, I can't believe this got closed for "not a real question". 1) It's not difficult to tell what is being asked. 2) The question is not ambiguous/incomplete/broad/unreasonable. This is quite an abuse!
  • Looks like it's currently way too easy to mistake the Downvote button ("I think this question doesn't show effort and isn't well asked") with the Close button ("I think it cannot be answered because of the following reason..."). Might be because Close votes are free.
  • Happened to be developing in Go and ran up against slice can only be compared to nil, and was wondering if there is an idiomatic golang way to check slice equality...if the equality operator is not defined by the language, then I find it reasonable to ask the most efficient way to accomplish it. Question did not need to be closed
  • Suggestion: for i, v := range a { if v != b[i] { return false } }.
  • @zzzz Careful, this will fail on different lengths.
  • This does not work if the element type does not support ==. Also, IIUC, Go does not have anything like generics. This means that you must copy n' paste this function for each element type that you want to support. This is obviously something that should ship with the language. In fact, it does (albeit with the magic of reflect), and Victor provides the answer. The fact that this is chosen above that answer, and more highly voted is simply maddening...
  • Go as a language tends to recommend not using reflection unless absolutely necessary. Yes, it would need to be done for each type but it is generally not something you do often anyways. Also, reflect.DeepEqual may do something you don't expect such as saying two different pointers are equal because the values they point to are equal.
  • @FiloSottile Length is checked beforehand, the loop is only reached if lengths differ.
  • A very useful answer. Regardless of the general reflect package performance, it is very nice to have a prepackaged deep equality function for use in test cases where simplicity and correctness are paramount.
  • I just ran a benchmark and reflect.DeepEqual is 150 times slower than a loop. Just FYI if anyone wants to use this method in production.
  • It does not compare randomly orderded slices with same items :(