Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pointers as Map index keys are not respected as equal #362

Closed
Whoaa512 opened this issue Aug 1, 2024 · 3 comments
Closed

Pointers as Map index keys are not respected as equal #362

Whoaa512 opened this issue Aug 1, 2024 · 3 comments

Comments

@Whoaa512
Copy link

Whoaa512 commented Aug 1, 2024

I've got a map of pointers to structs in a legacy code base and I'm unable to cleanly diff them b/c the compare pointers is not run on the keys

https://go.dev/play/p/yXCZ3SAZFj_R

@Whoaa512
Copy link
Author

Whoaa512 commented Aug 1, 2024

Ah I was able to workaround this with a custom compare

package main

import (
	"fmt"

	"github.com/google/go-cmp/cmp"
)

type Foo struct {
	Mapping map[*Bar]string
}

type Bar struct {
	Value int
}

func main() {
	fmt.Println("Hello, playground")

	bar1 := &Bar{Value: 1}
	bar2 := &Bar{Value: 1}

	want := &Foo{map[*Bar]string{bar1: "a"}}
	got := &Foo{map[*Bar]string{bar2: "a"}}

	// Define a custom comparator for Bar pointers
	barLess := func(a, b *Bar) bool {
		return a.Value < b.Value
	}

	// Create a custom option for comparing Foo structs
	opt := cmp.Comparer(func(x, y Foo) bool {
		return cmp.Equal(x.Mapping, y.Mapping, cmp.SortMaps(barLess))
	})

	diff := cmp.Diff(got, want, opt)
	fmt.Println(diff)
}

And further if I needed to compare a more complex struct, I could call cmp.Equal within my custom map sort func

@Whoaa512 Whoaa512 closed this as completed Aug 1, 2024
@dsnet
Copy link
Collaborator

dsnet commented Aug 1, 2024

Hi, I'm glad you figured it out with the use of cmpopts.SortMaps.

I suspect you can simplify this and just pass in cmpopts.SortMaps directly without wrapping it within a cmp.Comparer.

In fact, I believe doing so will provide a nicer diff.

@Whoaa512
Copy link
Author

Whoaa512 commented Aug 1, 2024

Yup that's what I ended up with after some more playing with it. The above was what Claude gave me to start with

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

No branches or pull requests

2 participants