Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Protobuf declarations and optional Fields in Go Struct (string pointers)

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

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

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

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

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

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

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?

like image 604
Tigraine Avatar asked Jul 15 '19 11:07

Tigraine


People also ask

Are all fields optional in Proto3?

In proto3, all fields are "optional" (in that it is not an error if the sender fails to set them). But, fields are no longer "nullable", in that there's no way to tell the difference between a field being explicitly set to its default value vs.

What is the difference between proto2 and Proto3?

Proto3 is the latest version of Protocol Buffers and includes the following changes from proto2: Field presence, also known as hasField , is removed by default for primitive fields. An unset primitive field has a language-defined default value.

Can Protobuf fields be null?

Protobuf treats strings as primitive types and therefore they can not be null.


1 Answers

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.

See Github issue #15.

Possible solutions:

  • 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.
like image 61
mattes Avatar answered Oct 21 '22 07:10

mattes