r3labs / diff

A library for diffing golang structures
Mozilla Public License 2.0
895 stars 84 forks source link

option for ignoring unexported fields #89

Open aexvir opened 2 years ago

aexvir commented 2 years ago

👋🏻 hey there I'm using this library as it has been the most consistent way to compare structs that I've found so far, thanks!

one feature that I'm missing is the option to ignore unexported fields from being compared and marked as differences, I know I can strip them by marshal/unmarshal but if that functionality would be provided by the library itself that would be amazing 🙂

I'm ok with implementing it myself and submitting a pr! I would like to know

I haven't checked the codebase yet, that's why I'm asking this 😅

aexvir commented 2 years ago

well... I just realized I can use the Filter function 😅 🙈

diff.Filter(
    func(path []string, parent reflect.Type, field reflect.StructField) bool {
        return field.IsExported()
    },
)

hmm... I guess that's the way to handle it, right? I'd be ok with either documenting it as example or adding an explicit option for this imo that would make it more obvious

wdyt?

purehyperbole commented 2 years ago

Hey @aexvir , thanks for raising the issue!

So there are a couple of ways to handle this:

  1. use diff.Filter as you suggest
  2. use diff:"-" tag on your structs

So 2 would be the best way to go if you have control over how those structs are defined:

type MyStruct struct {
    DontDiff string `diff:"-"`  // this will be ignored
    Diff     string             // will be diffed
}

I hope that helps!

aexvir commented 2 years ago

while I was aware of the diff:"-" struct tag I don't want to keep track of this and make sure to add it every time we add an unexported field; the filter works alright though, so I'm happy with that

I still think that maybe documenting this would be nice, as it didn't struck me as something obvious on the first place but up to you 🙂 feel free to close this issue if there is nothing else to discuss here

and thanks for the help!