Created
August 23, 2023 14:11
-
-
Save HalCanary/50c91e623a01aa6465449af8a950caf5 to your computer and use it in GitHub Desktop.
Golang Protobuff Message Copy Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"google.golang.org/protobuf/proto" | |
// type proto.Message interface { .... | |
// func proto.Merge(dst, src Message) | |
"[...]/foo" | |
// syntax = "proto3"; | |
// message Foo { | |
// int32 value = 1; | |
// } | |
) | |
// Is this the best way to do this? Can I make this better? | |
// Can I specify that *T must satisfy proto.Message? | |
func CopyProtoMessage[T any](src *T) (dst T) { | |
if srcMsg, ok := any(src).(proto.Message); ok { | |
if dstMsg, ok := any(&dst).(proto.Message); ok { | |
proto.Merge(dstMsg, srcMsg) | |
} | |
} | |
return | |
} | |
func main() { | |
f1 := foo.Foo{Value: 100} | |
f2 := CopyProtoMessage(&f1) | |
fmt.Printf("%d\n", f2.Value) | |
f3 := f1 // go-vet: assignment copies lock value to f3: [...]/foo.Foo contains | |
// google.golang.org/protobuf/internal/impl.MessageState contains sync.Mutex | |
fmt.Printf("%d\n", f3.Value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment