简体   繁体   中英

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.

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(&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?

(Footnote: I do not want to implement proto.Message , but have it provided or autogenerated)

Although wrapping is necessary, Protobuf conveniently provides wrappers for primitive types in 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:

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM