Skip to content

Instantly share code, notes, and snippets.

@HalCanary
Created August 23, 2023 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HalCanary/50c91e623a01aa6465449af8a950caf5 to your computer and use it in GitHub Desktop.
Save HalCanary/50c91e623a01aa6465449af8a950caf5 to your computer and use it in GitHub Desktop.
Golang Protobuff Message Copy Function
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