Skip to content

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

Open
@your-diary

Description

@your-diary

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

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)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions