r3labs / diff

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

Patching pointer values #72

Closed stoffen closed 2 years ago

stoffen commented 2 years ago

Hi, In the following I am unable to patch the struct. To me it seems that the diff holds a string and that the reflection machinery does not consider the target pointer. I am missing something here? Thanks:)

type Test struct {
    S *string `json:"s,omitempty"`
}

func TestPointerDiff(t *testing.T) {
    str1 := "before"
    t1 := Test{S: &str1}
    str2 := "after"
    t2 := Test{S: &str2}

    changelog, err := diff.Diff(t1, t2)
    assert.NoError(t, err)

    patchLog := diff.Patch(changelog, t1)
    assert.False(t, patchLog.HasErrors())
}
purehyperbole commented 2 years ago

Hey @stoffen ,

Thanks for raising the issue! Looks like it was an issue calling reflect.Set(). This should now be fixed with v2.14.3.

Please note, when calling patch, you will need to pass in a pointer to the value you're patching to, so your example would become:

    // pass in t1 as pointer
    patchLog := diff.Patch(changelog, &t1)
    assert.False(t, patchLog.HasErrors())
stoffen commented 2 years ago

Thanks, you just saved my day