Skip to content

cmp: clarify when a nil pointer reaches an Equal method - #399

Open
Sanjays2402 wants to merge 1 commit into
google:masterfrom
Sanjays2402:docs-equal-method-nil-pointer
Open

cmp: clarify when a nil pointer reaches an Equal method#399
Sanjays2402 wants to merge 1 commit into
google:masterfrom
Sanjays2402:docs-equal-method-nil-pointer

Conversation

@Sanjays2402

Copy link
Copy Markdown

Fixes #363.

The Equal documentation says a user-defined Equal method 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.

comparePtr short-circuits on a nil operand before dereferencing:

func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) {
	if vx.IsNil() || vy.IsNil() {
		s.report(vx.IsNil() && vy.IsNil(), 0)
		return
	}

A pointer is dereferenced before the method is considered, so a nil *T never reaches an Equal method declared on T. 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:

Equal declared on x=nil, y=non-nil method called
value type T false no
pointer type *T true yes

The 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.

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
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.

1 participant