docs: clarify Equal method is skipped when either value is nil - #397
docs: clarify Equal method is skipped when either value is nil#397Solaris-star wants to merge 2 commits into
Conversation
The package docs claimed x.Equal(y) runs "even if x or y is nil", but pointers/interfaces short-circuit on nil before tryMethod, so a nil receiver is never used. Document the actual behavior. Fixes #363
| // x.Equal(y) when both values are non-nil. If either value is nil, Equal | ||
| // reports whether both are nil without calling the method (so a nil | ||
| // receiver never panics). Otherwise, no such method exists and evaluation | ||
| // proceeds to the next rule. |
There was a problem hiding this comment.
Thanks for the PR, but I don't think this is quite correct.
The difference of whether Equal is called on nil is whether it is declared on a value receiver or not. Perhaps this is more clear:
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). The method is called even if x or y are nil and Equal
is declared on a pointer receiver. Otherwise, no such method exists and
evaluation proceeds to the next rule.
|
Thanks for the correction and the playground example. I updated the package docs in commit
|
Summary
Package docs for
Equalsaid the method is used even if x or y is nil.Actual behavior:
comparePtr/compareInterfacereport nil equality first and return, sotryMethodnever runs when either side is nil. Non-nil values still callEqualas documented.This matches issue #363 and avoids implying a nil receiver would be invoked (and potentially panic).
Test plan
*Twith value-receiverEqualdoes not print / call methodgo test ./cmp/Fixes #363