在gRPC protoc buffer golang中创建类型为Map[string]interface{}的变量

21

我正在使用grpc golang在客户端和服务器应用之间进行通信。 以下是protoc buffer的代码。

syntax = "proto3";
package Trail;

service TrailFunc {
  rpc HelloWorld (Request) returns (Reply) {}
}

// The request message containing the user's name.
message Request {
  map<string,string> inputVar = 1;
}
// The response message containing the greetings
message Reply {
  string outputVar = 1;
}

我需要在消息数据结构中创建一个类型为map[string]interface{}的字段inputVar,而不是map[string]string。如何实现?谢谢。


1
听起来好像是“你不想要”。但我猜 map<string,google.protobuf.Any> 可能会有用,也许? - Vatine
3个回答

21

proto3支持类型为Any

import "google/protobuf/any.proto";

message ErrorStatus {
  string message = 1;
  repeated google.protobuf.Any details = 2;
}

但是,如果你看它的实现方式,它只是这样的

message Any {
  string type_url = 1;
  bytes value = 2;
}

你需要自己定义这样的消息,可能需要使用反射和中间类型。

参见示例应用

https://github.com/golang/protobuf/issues/60


12

4

虽然使用起来有点啰嗦,但Protocol Buffers中的"struct"类型可能更接近于golang中的map[string]interface{}。

但就像interface{}一样,需要进行一些反射式的开销才能确定实际存储类型。

例如,请参见此处的评论:https://github.com/golang/protobuf/issues/370


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接