cmp: clarify when a nil pointer reaches an Equal method - #399
Open
Sanjays2402 wants to merge 1 commit into
Open
Conversation
The Equal documentation states that a user-defined Equal method is used 'even if x or y is nil'. This holds when the method is declared on the pointer type, but not when it is declared on the value type: comparePtr short-circuits on a nil operand before dereferencing, so a nil *T never reaches an Equal method declared on T. Document the distinction and add a regression test covering both receiver forms. Fixes google#363
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #363.
The
Equaldocumentation says a user-definedEqualmethod is used "even if x or y is nil". #363 reports this is not what happens. Both are partly right, and the difference is where the method is declared.comparePtrshort-circuits on a nil operand before dereferencing:A pointer is dereferenced before the method is considered, so a nil
*Tnever reaches anEqualmethod declared onT. When the method is declared on*T, it is found on the pointer itself and the documented behavior holds.Observed with the reproducer from the issue:
Equaldeclared onTfalse*TtrueThe behavior looks correct to me and changing it would give up nil-safety, so this only adjusts the documentation and adds a regression test covering both receiver forms.
Tested with
go test ./...on go1.26.3 (darwin/arm64); all packages pass. I also flipped one expectation to confirm the new test fails when the behavior changes.