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

Ignore all unexported fields #313

Open
dprotaso opened this issue Nov 15, 2022 · 4 comments
Open

Ignore all unexported fields #313

dprotaso opened this issue Nov 15, 2022 · 4 comments

Comments

@dprotaso
Copy link

Is there a way to ignore all unexported fields?

I have a library where I do comparisons and I need a generic way to skip unexported fields. ie. protobuf types.

@dsnet
Copy link
Collaborator

dsnet commented Nov 15, 2022

For unexported fields, take a look at https://pkg.go.dev/github.com/google/go-cmp/cmp/cmpopts#IgnoreUnexported.

For protobuf types, I highly recommend using https://pkg.go.dev/google.golang.org/protobuf/testing/protocmp#Transform instead.

@dprotaso
Copy link
Author

I was sorta hoping for

  1. Not needing to know the type (just a global option)
  2. Not needing to pull in a protobuf dependency to ignore unexported proto fields

@dsnet
Copy link
Collaborator

dsnet commented Nov 15, 2022

  1. Not needing to know the type (just a global option)

There's currently no ability to do that and it's unclear that it's a good idea to do that. Newly added fields that are actually semantically relevant may accidentally be ignored in the future just because all unexported fields are ignored.

You could build it yourself with:

opts := cmp.FilterPath(func(p cmp.Path) bool {
	sf, ok := p.Index(-1).(cmp.StructField)
	if !ok {
		return false
	}
	r, _ := utf8.DecodeRuneInString(sf.Name())
	return !unicode.IsUpper(r)
}, cmp.Ignore())
  1. Not needing to pull in a protobuf dependency to ignore unexported proto fields

If the program has a generated protobuf message, then it already depends on the protobuf module. If you're trying to build a general purpose comparison library on top of cmp, then you have to accept that being able to correctly compare all possible types is an impossible task. Option 1 is probably the best you can hope for.

@burdiyan
Copy link

@dsnet Thanks for the tip! I was also looking for a way to ignore unexpected fields recursively. Maybe worth adding this filter into the library, documenting the potential problems? Despite the issues I still find it very useful in many situations.

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

No branches or pull requests

3 participants