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

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?

我遇到了Protoc和我现有的包含可为空字符串字段的结构的问题。 p >

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

  type消息结构{
路径* string`json:“ path”`
} 
  code>  pre>  
 
 

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

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

 语法=“ proto3”; 
message消息{
字符串路径= 1; 
} 
  code>  pre> 
 
 

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

  type消息结构{  
路径字符串`protobuf:“ bytes,1,opt,name = Path,proto3” json:“ Path,omitempty”`
} 
  code>  pre> 
 
 

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

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

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.