-2

In the following code, a1 and a2 are same. They have same fields but with different orders (Book A and Book B are in different order). When I compare then using DeepEqual() method, the result says they are not equal. How to compare them and get a result that they are equal?

package main 

import ( 
    "fmt"
    "reflect"
) 

type Author struct { 
    name     string 
    Books []*Book
} 

type Book struct {  
    id int
    name string 
} 

func main() { 

    a1 := Author{ 
        name:    "Author Name", 
        Books: []*Book {
            {
                id: 1,
                name: "Book A",
            },
            {
                id: 2,
                name: "Book B",
            },
        },
    } 

    a2 := Author{ 
        name:    "Author Name", 
        Books: []*Book {
            {
                id: 2,
                name: "Book B",
            },
            {
                id: 1,
                name: "Book A",
            },          
        },
    }

    fmt.Println("Is a1 equal to a2: ", reflect.DeepEqual(a1, a2))
}

Result:

Is a1 equal to a2:  false
MAK
  • 1,915
  • 4
  • 20
  • 44

1 Answers1

2

Reference: reflect.DeepEqual

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.

And hence, it explains why it isn't working for you! The underlying array isn't or the corrensponding elements aren't equal.

shmsr
  • 3,802
  • 2
  • 18
  • 29