r3labs / diff

A library for diffing golang structures
Mozilla Public License 2.0
888 stars 80 forks source link

Differ without state #33

Closed voodoo-dn closed 4 years ago

voodoo-dn commented 4 years ago

Hi.

Could we do not use state when diff structs? https://github.com/r3labs/diff/blob/master/diff_struct.go#L101

purehyperbole commented 4 years ago

Hi

Thanks for a raising the issue.

Not sure I follow your question. Could you please clarify the issue you are seeing?

voodoo-dn commented 4 years ago

I ran server which receives updates for users and saves diffs between old data from db and new data from request and this diff saves to DB. But because service is live long process following part of code not clean up after diff calculation.

Maybe we can use stateless version of you great lib? Was justified stateful approach?

type Differ struct {
    SliceOrdering       bool
    DisableStructValues bool
    customValueDiffers  []ValueDiffer
    cl                  Changelog <----- every request filled this field and I had mess in DB
}

Thanks.

purehyperbole commented 4 years ago

Ok, I think I understand your issue. Are you reusing the same differ object multiple times between requests like:

d, _ := diff.NewDiffer(diff.SliceOrdering(true))

// use `d` for multiple requests
cl, _ d.Diff(a, b)

If so, you might want to use a new differ for each request.

Sorry if I've misunderstood the problem!

voodoo-dn commented 4 years ago

Okay, thanks. But what the reason of approach with state?

purehyperbole commented 4 years ago

It's only really internal state meant for constructing the changelog. As all of the internal diff functions are recurrsive, It's just somewhere convenient to store where the diff has gotten. I agree however that this might be confusing. I'll open a PR that resets this state on each call to Diff().

Thanks again for raising the PR! :)