Skip to content

docs: clarify Equal method is skipped when either value is nil - #397

Open
Solaris-star wants to merge 1 commit into
google:masterfrom
Solaris-star:docs/363-equal-nil-method
Open

docs: clarify Equal method is skipped when either value is nil#397
Solaris-star wants to merge 1 commit into
google:masterfrom
Solaris-star:docs/363-equal-nil-method

Conversation

@Solaris-star

Copy link
Copy Markdown

Summary

Package docs for Equal said the method is used even if x or y is nil.

Actual behavior: comparePtr / compareInterface report nil equality first and return, so tryMethod never runs when either side is nil. Non-nil values still call Equal as documented.

This matches issue #363 and avoids implying a nil receiver would be invoked (and potentially panic).

Test plan

  • Manual repro: nil vs non-nil *T with value-receiver Equal does not print / call method
  • go test ./cmp/

Fixes #363

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 google#363
Comment thread cmp/compare.go
// 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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

See https://go.dev/play/p/Jf2jQPmgnZx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants