2019-07-15 11:43
浏览 597

Go Protobuf声明和Go Struct中的可选字段(字符串指针)

I am running into a bit of a problem with Protoc and my existing struct that contains nullable string fields.

The struct I am trying to serialize for transmission contains a bunch of fields that are nullable in json (so we can distinguish between null, "" and a set value).

type Message struct {
  Path *string `json:"path"`

So if a user sends a empty json string {} the Path will be nil and not "", whereas {"path":""} is also valid and a different case from {"path": null}.

The proto3 declaration I came up with obviously looks like this (and is optional as required and optional got dropped from proto3:

syntax = "proto3";
message Message {
  string Path = 1;

After running Protoc I end up with a struct that looks like this and all values are string and no way to declare them as *string:

type Message struct {
  Path string `protobuf:"bytes,1,opt,name=Path,proto3" json:"Path,omitempty"`

Obviously I can't assign to this array from my existing struct. But even if I were to write the tedious mapping code with target.Path = *source.Path with the appropriate null pointer checks etc I'd loose the triple meaning of my source struct (nil, "", "value").

Any suggestions on how to proceed here or if there is an extension to the Go Protobuf to do this? Or how would one go about describing this proto declaration?

图片转代码服务由CSDN问答提供 功能建议


我要序列化以进行传输的结构包含一堆在json中可为空的字段(因此我们可以区分 null “” 和设置值)。

路径* string`json:“ path”`

因此,如果用户发送一个空的json字符串 {} ,则路径将为 nil 而不是“” {“ path”:“”} 也有效,并且大小写与 {“ path”:null} 不同。

我想出的 proto3 声明显然是这样的(并且是可选的,因为 required optional 从proto3中删除了:

 语法=“ proto3”; 
字符串路径= 1; 

运行Protoc之后,我结束 与一个结构,我 看起来像这样,所有值都是 string ,无法将它们声明为 * string

路径字符串`protobuf:“ bytes,1,opt,name = Path,proto3” json:“ Path,omitempty”`

显然我 无法从我现有的结构分配给此数组。 但是即使我用适当的空指针检查用 target.Path = * source.Path 编写乏味的映射代码,我也会放弃源代码结构的三重含义( nil “”“ ” value“ )。

关于如何进行此处操作或是否有Go Protobuf扩展的任何建议? 或将如何描述此原始声明?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dousu1900 2019-07-15 22:05

    Proto3 returns the Zero Value even if a field isn't set. Currently there is no way to distinguish if a field has been set or not.

    See Github issue #15.

    Possible solutions:

    Probably not a solution:

    Write the tedious mapping code with target.Path = *source.Path with the appropriate null pointer.

    ... as this won't work for int types where the zero value is 0.

    点赞 打赏 评论

相关推荐 更多相似问题