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>
diff --git a/cmd/protoc-gen-go/internal_gengo/well_known_types.go b/cmd/protoc-gen-go/internal_gengo/well_known_types.go
index 4fc1cd7..7365075 100644
--- a/cmd/protoc-gen-go/internal_gengo/well_known_types.go
+++ b/cmd/protoc-gen-go/internal_gengo/well_known_types.go
@@ -19,6 +19,16 @@
 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("//")
diff --git a/types/known/anypb/any.pb.go b/types/known/anypb/any.pb.go
index 4a7f5bb..061a9ee 100644
--- a/types/known/anypb/any.pb.go
+++ b/types/known/anypb/any.pb.go
@@ -161,6 +161,15 @@
 	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.
 //