Golang gRPC 默认值
Golang gRPC default values
给定以下 protobuf 定义:
message MyMessage {
string Foo = 1;
int From = 2;
int To = 3;
}
然后我有一个案例,我只想从客户端发送 Foo 字符串,没问题。
问题出现在服务器中,我想知道 From 和 To 是否有值(UNIX 时间戳)。
如果客户端未明确设置该值,则 Go 会将其设置为 0,这是一个完全有效的 Unix 时间戳。在这一点上,我不知道客户是打算给我 1970-01-01 00:00:00 还是打算留空。
我可以添加两个布尔值来说明客户端是否设置了 From 和 To,但我觉得应该有比这更优雅的解决方案。
有没有办法真正查明客户端是否打算发送空值,或者它是否实际将值设置为 0
? ""
对于字符串等也是如此。
您无法区分缺少的字段和在 proto3 中设置为默认值的字段。这是设计使然。在 Issue 1606:
中引用 xfxyjwf
Rationale of removing field presence in proto3:
Field presence in proto2 has caused confusions and it complicates the semantics, e.g. one
has to distinguish between absence fields vs fields set to their default values; users usually
check presence before accessing the fields which is unnecessary. We believe in most cases,
field presence info is not needed.
Removing field presence makes Proto3 significantly easier to implement with open struct
representations, as in languages like Android Java (go/nano-proto), or Go. The easier
implementation in turn makes it better accessible to external implementer communities.
- If such presence info is explicitly needed, there are several workarounds, e.g. wrappers, explicit
has_field boolean. Oneof can also be used if backward wire compatibility with proto2 optional
field is desired.
给定以下 protobuf 定义:
message MyMessage {
string Foo = 1;
int From = 2;
int To = 3;
}
然后我有一个案例,我只想从客户端发送 Foo 字符串,没问题。 问题出现在服务器中,我想知道 From 和 To 是否有值(UNIX 时间戳)。 如果客户端未明确设置该值,则 Go 会将其设置为 0,这是一个完全有效的 Unix 时间戳。在这一点上,我不知道客户是打算给我 1970-01-01 00:00:00 还是打算留空。
我可以添加两个布尔值来说明客户端是否设置了 From 和 To,但我觉得应该有比这更优雅的解决方案。
有没有办法真正查明客户端是否打算发送空值,或者它是否实际将值设置为 0
? ""
对于字符串等也是如此。
您无法区分缺少的字段和在 proto3 中设置为默认值的字段。这是设计使然。在 Issue 1606:
中引用 xfxyjwf
Rationale of removing field presence in proto3:
Field presence in proto2 has caused confusions and it complicates the semantics, e.g. one has to distinguish between absence fields vs fields set to their default values; users usually check presence before accessing the fields which is unnecessary. We believe in most cases, field presence info is not needed.
Removing field presence makes Proto3 significantly easier to implement with open struct representations, as in languages like Android Java (go/nano-proto), or Go. The easier implementation in turn makes it better accessible to external implementer communities.
- If such presence info is explicitly needed, there are several workarounds, e.g. wrappers, explicit has_field boolean. Oneof can also be used if backward wire compatibility with proto2 optional field is desired.