mirror of
https://github.com/protocolbuffers/protobuf-go.git
synced 2024-12-26 21:24:22 +00:00
types/known/anypb: add New constructor
While the MarshalFrom method and function are more flexible since it permits the reuse of an existing Any, the most common use case by far is to construct a new Any. Optimize for that use case by providing a constructor that directly returns a new Any instance. We do not provide a variant that accepts a MarshalOptions since the more flexible MarshalFrom function can be used for that. Change-Id: Iab0219229c7d3aaa7390a2340a4f248002995293 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/237997 Reviewed-by: Damien Neil <dneil@google.com>
This commit is contained in:
parent
bfc31022a5
commit
0084168af8
@ -19,6 +19,16 @@ import (
|
||||
func genMessageKnownFunctions(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) {
|
||||
switch m.Desc.FullName() {
|
||||
case genid.Any_message_fullname:
|
||||
g.P("// New marshals src into a new Any instance.")
|
||||
g.P("func New(src ", protoPackage.Ident("Message"), ") (*Any, error) {")
|
||||
g.P(" dst := new(Any)")
|
||||
g.P(" if err := dst.MarshalFrom(src); err != nil {")
|
||||
g.P(" return nil, err")
|
||||
g.P(" }")
|
||||
g.P(" return dst, nil")
|
||||
g.P("}")
|
||||
g.P()
|
||||
|
||||
g.P("// MarshalFrom marshals src into dst as the underlying message")
|
||||
g.P("// using the provided marshal options.")
|
||||
g.P("//")
|
||||
|
@ -161,6 +161,15 @@ type Any struct {
|
||||
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
|
||||
}
|
||||
|
||||
// New marshals src into a new Any instance.
|
||||
func New(src proto.Message) (*Any, error) {
|
||||
dst := new(Any)
|
||||
if err := dst.MarshalFrom(src); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
// MarshalFrom marshals src into dst as the underlying message
|
||||
// using the provided marshal options.
|
||||
//
|
||||
|
Loading…
Reference in New Issue
Block a user