[英]How to use `google.protobuf.Any` in Go with primitive types?
I have a message like我有一条消息
message Response {
google.protobuf.Any id = 1;
string message = 3;
}
and I would like to encode either an int32
or string
in ID.我想在 ID 中编码一个int32
或string
。
I can achieve this by making some wrapper type我可以通过制作一些包装类型来实现这一点
message IntWrapper {
int32 id = 1;
}
and using ptypes.MarshalAny
from github.com/golang/protobuf/ptypes
to marshal my new types since they implement proto.Message
.并使用ptypes.MarshalAny
中的github.com/golang/protobuf/ptypes
来编组我的新类型,因为它们实现proto.Message
。
ptypes.MarshalAny(&myproto.IntWrapper{Id: 1})
I'd like to do this without the wrappers.我想在没有包装的情况下做到这一点。 Are there implementations of proto.Message
somewhere for plain int32
's or string
's or another way to do this?对于普通的int32
或string
或其他方式,是否有proto.Message
的实现?
(Footnote: I do not want to implement proto.Message
, but have it provided or autogenerated) (脚注:我不想实现proto.Message
,但提供或自动生成它)
Although wrapping is necessary, Protobuf conveniently provides wrappers for primitive types in google.protobuf.wrappers.proto
.尽管包装是必要的,但 Protobuf 方便地为google.protobuf.wrappers.proto
中的原始类型提供了包装器。
Here is an example of how to use google.protobuf.Any
with primitive types in Go using the packages generated from these protos:下面是如何使用google.protobuf.Any
与 Go 中的原始类型使用从这些 protos 生成的包的示例:
package main
import (
"fmt"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func main() {
strWrapper := wrapperspb.String("foo")
strAny, _ := anypb.New(strWrapper)
fmt.Println(strAny)
intWrapper := wrapperspb.Int32(123)
intAny, _ := anypb.New(intWrapper)
fmt.Println(intAny)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.