dongshenchi5364 2019-02-04 13:13
浏览 60
已采纳

协议缓冲区零值(整数)

I have a Go struct what we are using currently in our restful API which looks like this:

type Req struct {
  Amount *int
}

I'm using pointer here, because if the Amount is nil, it means the Amount was not filled, if the Amount isn't nil, but it's zero, it means the field was filled, but the value is zero.

When we started to change to protofiles and we want to use it like, the main API get's the request as HTTP API and send it to the next service through gRPC with the same protofile I faced with the issue, the proto3 can't generate pointer for the Amount. That's fine because the protocol buffers designed for the purpose of sending data between separated systems, but how can I handle the issue above, because if I get the request I can't decide that the Amount is nil or just zero.

  • 写回答

1条回答 默认 最新

  • douxian3828 2019-02-04 13:22
    关注

    proto3 doesn't distinguish between zero and absent; the concepts of defaults and implicit vs explicit values disappeared:

    • the default value is always zero (or false, etc)
    • if the value is zero, it isn't sent; otherwise, it is

    What you're after is more possible with proto2. Alternatively, just add a separate field to indicate that you have a value for something:

    message Req {
        int amount = 1;
        bool amountHasValue = 2;
    }
    

    Or use a nested sub-message, i.e.

    message Foo {
        Bar bar = 1;
    }
    message Bar {
        int amount = 1;
    }
    

    (so; without a value you just send a Foo; with a value, you send a Foo with a Bar, and whatever the amount is: it is)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改