gpt4 book ai didi

go - Golang gRPC默认值

转载 作者:行者123 更新时间:2023-12-01 20:26:53 25 4
gpt4 key购买 nike

给定以下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还是要留空。

我可以添加两个 bool 值,说明客户是否设置了“从”和“到”,但是我觉得应该有一个比这更优雅的解决方案。

有没有一种方法可以真正找出客户端是否打算发送空值,或者是否将值实际设置为 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.

关于go - Golang gRPC默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60523226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com