如何在ProtoBuffer中表示一个HashMap实例?

huangapple go评论71阅读模式
英文:

How to represent a HashMap<Object, Double> instance in ProtoBuffer?

问题

I need to include an instance of the following class as a field in a protocol buffer schema:

public final class Metrics extends HashMap<Object, Double> {
}

but when I add something like:

map<bytes, double> metrics = 2;

I effectively get the message "Map key cannot be float, double, bytes, message, or enum types".

One approach I've thought of was to turn the objects (keys) into bytes and then into base64 keys to create a new map, which would be the actual map to be sent to the wire (then reverse these operations when it got to the other side). But this seems too expensive, and I feel like I would have to create an instance of the input streams (and close them) for each entry.

Is there a known approach for this case? How would you do it?
I did not find any example of this.

Thanks

英文:

I need to include an instance of the following class as a field in a protocol buffer schema:

public final class Metrics extends HashMap&lt;Object, Double&gt; {
}

but when I add something like:

map&lt;bytes, double&gt; metrics = 2;

I effectively get the message Map key cannot be float, double, bytes, message, or enum types.

One approach I've thought of was to turn the objects (keys) into bytes and then to base64 keys to create a new map, which would be the actual map to be sent to the wire (then reverse these operations when it got to the other side). But this seems too expensive and I feel like I would have to create an instance of the input streams (and close them) for each entry.

Is there a known approach for this case? How would you do it?
I did not find any example of this.

Thanks

答案1

得分: 1

你可以使用键值对列表来模拟映射(在proto3引入映射之前是这样做的),并将它们回溯到proto2:

message Metric {
  bytes key = 1;
  double value = 2;
}

repeated Metric metrics = 2;
英文:

You can emulate map with a list of key-value pairs (this is how it was done before introduction of maps in proto3 and backporting them to proto2):

message Metric {
  bytes key = 1;
  double value = 2;
}

repeated Metric metrics = 2;

huangapple
  • 本文由 发表于 2020年6月29日 06:10:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/62628751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定