Enum Definitions in Protobuf

Define enum types in protobuf with named constants and numeric values. Covers the required zero value, aliases, reserved values, and nested enum definitions.

Enums & Oneof

Detailed Explanation

Defining Enumerations in Protobuf

Enums define a fixed set of named integer constants. They are essential for representing states, categories, and modes in a type-safe manner.

syntax = "proto3";

enum Priority {
  PRIORITY_UNSPECIFIED = 0;
  PRIORITY_LOW = 1;
  PRIORITY_MEDIUM = 2;
  PRIORITY_HIGH = 3;
  PRIORITY_CRITICAL = 4;
}

message Task {
  string title = 1;
  string description = 2;
  Priority priority = 3;
  Status status = 4;

  // Nested enum
  enum Status {
    STATUS_UNSPECIFIED = 0;
    STATUS_TODO = 1;
    STATUS_IN_PROGRESS = 2;
    STATUS_DONE = 3;
    STATUS_ARCHIVED = 4;
  }
}

The Zero Value Rule

In proto3, the first enum value must be zero and serves as the default value. Convention is to name it *_UNSPECIFIED or *_UNKNOWN. This is critical for forward compatibility: if a message is received with an unknown enum value, it is stored as the numeric value but may be reported as the zero value by language-specific accessors.

Naming Conventions

Google's style guide recommends:

  • Enum type names: PascalCase (e.g., OrderStatus)
  • Value names: SCREAMING_SNAKE_CASE prefixed with the enum type (e.g., ORDER_STATUS_PENDING)
  • The prefix prevents naming conflicts when multiple enums are in scope

Reserved Values and Names

Use reserved to prevent reuse of deprecated field numbers or names:

enum Status {
  reserved 2, 15, 9 to 11;
  reserved "OLD_STATUS", "LEGACY_STATUS";
  STATUS_UNSPECIFIED = 0;
  STATUS_ACTIVE = 1;
}

Aliases

Setting option allow_alias = true; lets multiple names map to the same numeric value, useful for backward compatibility when renaming enum values.

Use Case

Modeling finite state machines (order statuses, task priorities), API error codes, permission levels, feature categories, or any field with a known set of valid values.

Try It — Protobuf Definition Parser

Open full tool