PumpkinSeed
PumpkinSeed

Reputation: 3113

Protocol buffer zero value for integer

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.

Upvotes: 4

Views: 4216

Answers (2)

ddrake12
ddrake12

Reputation: 943

Update July 2023

The current Accepted answer is no longer true. proto3 now supports the optional parameter which will generate a field with a pointer satisfying the original question. See https://protobuf.dev/reference/go/go-generated/#singular-scalar-proto3

For example:

message Foo {
   optional int32 bar = 1;
}

generates

type Foo struct {
   bar *int32
}

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1063393

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)

Upvotes: 4

Related Questions