-
Notifications
You must be signed in to change notification settings - Fork 1.6k
updating wrapper.StringValue with proto.Merge; nil pointer vs zero-value #1050
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I'm afraid Java's |
@neild That's what I suspected, then! I'm guessing there are no unofficial equivalents either? Either way, I'm not particularly proud of this piece of code, but just in case anyone stumbles upon this, you can always do something like this: package merge
import (
"bytes"
"encoding/json"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/imdario/mergo"
)
// Merge is the slowest, unsafest way to merge two proto messages preserving
// wrapper types' zero values.
func Merge(dst, src proto.Message) {
marshaler := jsonpb.Marshaler{}
sourceBuf := &bytes.Buffer{}
err := marshaler.Marshal(sourceBuf, src)
if err != nil {
panic(err)
}
destinationBuf := &bytes.Buffer{}
err = marshaler.Marshal(destinationBuf, dst)
if err != nil {
panic(err)
}
sourceMap := make(map[string]interface{})
destinationMap := make(map[string]interface{})
err = json.NewDecoder(sourceBuf).Decode(&sourceMap)
if err != nil {
panic(err)
}
err = json.NewDecoder(destinationBuf).Decode(&destinationMap)
if err != nil {
panic(err)
}
if err := mergo.Merge(&destinationMap, sourceMap, mergo.WithOverride); err != nil {
panic(err)
}
finalDestinationBuffer := &bytes.Buffer{}
err = json.NewEncoder(finalDestinationBuffer).Encode(destinationMap)
if err != nil {
panic(err)
}
dst.Reset()
err = jsonpb.Unmarshal(finalDestinationBuffer, dst)
if err != nil {
panic(err)
}
}
func deleteNils(in map[string]interface{}) {
for k, v := range in {
if m, ok := v.(map[string]interface{}); ok {
deleteNils(m)
}
if v == nil {
delete(in, k)
}
}
} As it says in the comment, it truly is absolutely horrible and I'll probably never get hired again if anyone ever sees this but it definitely works! |
Hello all,
Given this message:
this code:
will output
"Some string"
.Is there any way at all to make it output
""
? In other words, is there any way to update theS
wrapper field it with its corresponding zero value if this has to be merged into an existing struct? I thought that was the whole point of the wrapper types.For context, I'm pulling a record off storage, updating only some fields, and storing it back. The storage that I'm using only supports PUT operations so I can't just send some values, I have to send the whole message, hence the need to merge.
Regards
The text was updated successfully, but these errors were encountered: