mennanov / fieldmask-utils

Protobuf Field Mask Go utils
MIT License
229 stars 26 forks source link

Unexpected copy results when mask is empty #18

Closed yangtau closed 2 years ago

yangtau commented 2 years ago
    type A struct {
        B string
    }
    a := &A{
        B: "b",
    }
    mask, _ := fm.MaskFromPaths([]string{}, generator.CamelCase)
    dest := &A{}
    _ = fm.StructToStruct(mask, a, dest)

    fmt.Println(dest)
    // got: &{b}
    // expect: &{}

I am confused with the copy result. When the mask (paths) is empty, what I expect is nothing will be copied. But the result is everything is copied.

I am wondering what's the purpose to copy everything when the mask is empty?

mennanov commented 2 years ago

Since the mask is recursive an empty mask assumes that everything should be copied. Consider the following mask: a{b{d}, c}. If the fielda.c is a struct then it is expected that the entire struct is copied whereas for the field a.b only the field d should be copied.

If you don't want this behavior for the root mask you should check if the mask is empty before calling StructToStruct.