google / google/go-cmp

The documentation "Equal is called even if x or y is nil" seems incorrect.

Open
#363 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
4.7k
Forks
243
PR merge metrics
No merged PRs in 30d

Description

The documentation of `Equal()` (introduced in #63) seems incorrect (emphasis mine):

> If the values have an Equal method of the form "(T) Equal(T) bool" or "(T) Equal(I) bool" where T is assignable to I, then use the result of x.Equal(y) ***even if x or y is nil***. Otherwise, no such method exists and evaluation proceeds to the next rule.

As far as I tested, `x.Equal(y)` is NOT called if `x == nil` or/and `y == nil`.

[playground](https://go.dev/play/p/fkD4-N98-Ai)

```go
package main

import (
"fmt"

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

type S struct {
V *T
}

type T struct {
}

func (t1 T) Equal(t2 T) bool {
fmt.Println("hello")
return true
}

func main() {
{
s1 := S{
V: &T{},
}
s2 := S{
V: &T{},
}
fmt.Println(cmp.Equal(s1, s2)) //=> hello, hello, true (as expected)
}

{
s1 := S{
V: nil,
}
s2 := S{
V: &T{},
}
// s1.V.Equal(*s2.V) //panics
fmt.Println(cmp.Equal(s1, s2)) //=> false (doesn't panic)
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.