我在使用Protoc时遇到了问题,因为我的现有结构包含可为空的字符串字段。
我正在尝试序列化要传输的结构,其中包含许多在json中可为空的字段(这样我们可以区分null
、""
和一个已设置的值)。
type Message struct {
Path *string `json:"path"`
}
如果用户发送空的JSON字符串
{}
,则路径将为nil
而不是""
,而{"path":""}
也是有效的,并且与{"path": null}
不同。我提出的
proto3
声明显然如下(并且作为可选项,required
和optional
被从proto3中删除了):syntax = "proto3";
message Message {
string Path = 1;
}
在运行 Protoc 之后,我得到了一个结构体,它看起来像这样,所有的值都是
string
,无法将其声明为 *string
。type Message struct {
Path string `protobuf:"bytes,1,opt,name=Path,proto3" json:"Path,omitempty"`
}
显然,我不能从现有的结构中分配给这个数组。但即使我写了繁琐的映射代码,并使用适当的空指针检查来编写
target.Path = *source.Path
,我也会失去源结构的三重含义(nil
、""
、"value"
)。您有什么建议或者是否有Go Protobuf扩展可以解决这个问题?或者如何描述这个proto声明呢?