How to compare if two structs, slices or maps are equal?

后端 未结 5 2274
醉话见心
醉话见心 2020-11-28 02:30

I want to check if two structs, slices and maps are equal.

But I\'m running into problems with the following code. See my comments at the relevant lines.

<         


        
5条回答
  •  孤城傲影
    2020-11-28 02:53

    reflect.DeepEqual is often incorrectly used to compare two like structs, as in your question.

    cmp.Equal is a better tool for comparing structs.

    To see why reflection is ill-advised, let's look at the documentation:

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

    ....

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

    If we compare two time.Time values of the same UTC time, t1 == t2 will be false if their metadata timezone is different.

    go-cmp looks for the Equal() method and uses that to correctly compare times.

    Example:

    m1 := map[string]int{
        "a": 1,
        "b": 2,
    }
    m2 := map[string]int{
        "a": 1,
        "b": 2,
    }
    fmt.Println(cmp.Equal(m1, m2)) // will result in true
    

提交回复
热议问题