AIP-149

Unset field values

In many messages, many fields are optional: the user is not required to provide them, or for output fields, the service might not populate the field.

In most cases, there is no meaningful difference between setting it to a default value (such as 0) as opposed to not setting it at all; however, occasionally this distinction is meaningful.

Guidance

Services defined in protocol buffers should use the optional keyword for primitives if and only if it is necessary to distinguish setting the field to its default value (0, false, or empty string) from not setting it at all:

// A representation of a book in a library.
message Book {
  // The name of the book.
  string name = 1;

  // The rating for the book, from 0 to 5.
  // 0 is distinct from no rating.
  optional int32 rating = 2;
}

Important: Services should not need to distinguish between the default value and unset most of the time; if an alternative design does not require such a distinction, it is usually preferred. In practice, this means optional should only ever be used for integers and floats.