What is a oneof in Protocol Buffers and when would you use it?
Last updated
A oneof groups fields so at most one is set at a time (a union type): setting one clears the others, and generated code exposes a case accessor.
Use it for mutually exclusive alternatives, such as a response that is either a
resultor anerror.It cannot contain
repeatedfields or maps. Moving an existing field into or out of aoneofbreaks wire semantics.
- https://protobuf.dev/programming-guides/proto3/
- https://protobuf.dev/overview/
- https://medium.com/@phiraphat.sukkasem/grpc-oneof-response-the-secret-weapon-that-turns-ugly-grpc-responses-into-beautiful-type-safe-531c3e633086
- https://victoriametrics.com/blog/go-protobuf-basic/
- https://www.santekno.com/en/43-leveraging-oneof-in-protobuf/
- https://badgerbadgerbadgerbadger.dev/posts/misc/2024-12-05-oneofs-in-protobuf/