compare and copy one instance of the same go struct to another updated instance

28 views Asked by At

I have a nested go struct, and i have two instances of it. The original and the new one. I need a way to compare these two instances and copy all the fields (if they are filled and skip the empty one's) from the new instance to the original instance - this would ensure that any field not defined in the new instance will not hamper that field in the original instance - thus retaining the data.

I tried using reflect package but unable to make compare and copy. Its overwriting the entire original struct. I cannot use any custom struct tags cause these structs are coming in from protobuf code - FYI

type Data1 struct {
    BlobStorage []BlobStorage1
}

type BlobStorage1 struct {
    ResourceMetadata ResourceMetadata1
    ResourceData     ResourceData1
}

type ResourceMetadata1 struct {
    ARI       string
    Labels    []Labels1
    DependsOn DependsOn1
}

type Labels1 struct {
    Key         string
    Value       string
    Description string
}

type ResourceData1 struct {
    Name   string
    Region string
}

type DependsOn1 struct {
    Default []string
    Custom  []string
}

    Original := &Data1{
        BlobStorage: []BlobStorage1{
            {
                ResourceMetadata: ResourceMetadata1{
                    ARI:       "test",
                    Labels:    []Labels1{
                        {
                            Key:         "demo",
                            Value:       "",
                            Description: "",
                        },
                    },
                    DependsOn: DependsOn1{
                        Default: []string{"asdasda"},
                        Custom:  []string{},
                    },
                },
                ResourceData:     ResourceData1{
                    Name:   "",
                    Region: "oldregion",
                },
            },
        },
    }

    New := &Data1{
        BlobStorage: []BlobStorage1{
            {
                ResourceMetadata: ResourceMetadata1{
                    ARI:       "",
                },
                ResourceData:     ResourceData1{
                    Name:   "new",
                    Region: "newrgion",
                },
            },
        },
    }

From the above code - the original instance of the Data1 struct should have all the field values intact and only the "Name" and "Region" fields will be updated from the New instance of the struct - Note how that ARI is empty - so the copier should skip that field.

Would really appreciate any sort of help here - Thanks alot in advance

0

There are 0 answers