Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Protobuf Language

oneof, optional and Well-Known Types

Use oneof for alternatives, optional for field presence, and the well-known types Timestamp, Duration, Empty, Any, Struct and FieldMask. Includes runnable Go stand-ins.

Plain proto3 fields cannot say "this one was not provided", and they cannot say "exactly one of these". Protobuf fixes both with optional and oneof. Google also ships a library of well-known types for common ideas such as timestamps and durations, so every API does not invent its own. This lesson covers all three, with Go stand-ins that model their behavior.

The real compiler is not available here, so .proto code is read-only; the Go programs use only the standard library.

optional: field presence

Recall from messages and scalar types that a plain int32 cannot distinguish zero from "unset". Marking the field optional adds presence tracking:

PROTO
message UpdateProductRequest {
  int64 id = 1;
  optional string name = 2;
  optional int32 stock = 3;
}

In Go, optional scalars become pointers (*int32); nil means "not set". In Java you get hasStock(), in Python HasField("stock"). Message-typed fields always track presence, so they never need optional.

Stand-in 1: presence with pointers

Go Stand-in: optional as a pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

oneof: exactly one alternative

PROTO
message PaymentMethod {
  oneof method {
    CreditCard card = 1;
    BankTransfer transfer = 2;
    string voucher_code = 3;
  }
}

Rules:

  • At most one field in the group is set at a time. Setting another one clears the previous one.
  • Fields share the same message; they have normal, distinct field numbers.
  • You cannot use repeated or map fields inside a oneof, but a field can be a message that contains them.
  • Reading code can ask which one is set: GetMethod() returns an interface in Go (switch on its type), getMethodCase() in Java, WhichOneof("method") in Python.
  • If the wire carries two members of one group, the last one parsed wins.

Adding a new member to a oneof is compatible with old readers (they see "none set"). Moving an existing field into or out of a oneof is not safe if data already exists.

Stand-in 2: oneof as an interface plus a type switch

This is how the Go generator represents oneof: an interface implemented by one wrapper type per member.

Go Stand-in: oneof in Go

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Always handle the "none set" case: a field that is absent is the default state, and a newer sender may add members you do not know.

Well-known types

Google publishes standard messages in google/protobuf/*.proto. Import them and use them like any other type:

PROTO
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";
import "google/protobuf/empty.proto";
import "google/protobuf/field_mask.proto";

message Event {
  google.protobuf.Timestamp created_at = 1;
  google.protobuf.Duration  length     = 2;
}
Type Contents Use for
Timestamp int64 seconds since Unix epoch + int32 nanos A point in time (UTC)
Duration int64 seconds + int32 nanos A span of time, can be negative
Empty nothing Methods with no input or output
FieldMask repeated string paths Partial updates and field selection
Any type_url + serialized bytes A message of a type chosen at runtime
Struct, Value, ListValue JSON-like dynamic data Free-form JSON documents
Wrapper types (StringValue, Int32Value, ...) A single scalar in a message Presence for scalars (mostly replaced by optional)

Prefer Timestamp over strings such as "2025-01-01" or raw integers: every language converts it to its native date type.

Stand-in 3: Timestamp and Duration conversions

Real libraries convert between Timestamp and each language's time type. This stand-in does the same arithmetic in Go.

Go Stand-in: Timestamp and Duration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

FieldMask for partial updates

optional can tell you which scalar was set, but updates often involve many fields and nested paths. A FieldMask lists the paths the caller wants to change:

PROTO
message UpdateProductRequest {
  Product product = 1;
  google.protobuf.FieldMask update_mask = 2;
}

A request with update_mask { paths: "name" paths: "stock" } changes only those two fields, even when other fields in product hold zero values. Many Google APIs use this pattern, and the style guide recommends it for update methods.

Choosing between the tools

  • Need "unset versus zero" for one scalar: optional.
  • Need "exactly one of N alternatives": oneof.
  • Need partial updates of many fields: FieldMask.
  • Need a type chosen at runtime: Any, used sparingly, because it weakens the contract.
  • Need dynamic JSON: Struct.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Go represent an optional int32 field?

    Pointers give presence: nil means the sender did not provide the field.
  2. 2. What happens when you set a second field in the same oneof?

    At most one member is set. Setting one clears the others.
  3. 3. Which well-known type is right for 'the time this order was placed'?

    Timestamp is seconds plus nanos since the Unix epoch and maps to each language's date type.
  4. 4. What does a FieldMask contain?

    It names which paths matter, so partial updates are unambiguous.
  5. 5. Why must code handling a oneof always include a 'none set' case?

    Absent or unknown members are normal in evolving contracts.

Summary

  • optional adds presence to scalars; Go uses pointers.
  • oneof models alternatives; the generated type is an interface in Go.
  • Well-known types such as Timestamp, Duration, Empty, FieldMask, Any and Struct avoid reinventing common shapes.
  • Use a FieldMask for partial updates of several fields.
  • Always handle unset and unknown cases.

Next: Packages, Imports and Options