Go结构中的Go Protobuf声明和可选字段(字符串指针) [英] Go Protobuf declarations and optional Fields in Go Struct (string pointers)

查看:88
本文介绍了Go结构中的Go Protobuf声明和可选字段(字符串指针)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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"`
}

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

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}.

我想出的 proto3 声明看起来像这样(并且是可选的,因为 required optional 从proto3中删除了

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;
}

运行Protoc之后,我得到的结构看起来像这样,所有值都是 string ,无法将它们声明为 * string :

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"`
}

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

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").

关于如何继续执行此操作或是否有Go Protobuf扩展来执行此操作的任何建议?还是会去描述这个原始声明?

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?

推荐答案

Proto3返回零值即使未设置字段.当前无法区分是否已设置字段.

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.

请参阅Github问题#15 .

See Github issue #15.

可能的解决方案:

  • Use proto2 instead of proto3.
  • Use gogoproto's nullable extension.
  • Use the google.protobuf.FieldMask extension, see Common Design Patterns from the Google API Design Guide: Partial Responses and Output Fields.

这篇关于Go结构中的Go Protobuf声明和可选字段(字符串指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆