Skip to content

Go Proto Enum

DodaTech 1 min read

In this tutorial, you'll learn about Protobuf: Enum Options. We cover key concepts, practical examples, and best practices.

Protobuf enums -- Define enums with proper naming to avoid Go compilation errors and support value aliases.

The Problem

Protobuf enums generate Go constants. Enum values must be unique (without allow_alias). The first value must be 0.

Wrong

syntax = "proto3";
enum Status {
    ACTIVE = 0;
    INACTIVE = 1;
    ACTIVE = 2; // Duplicate name!
}

Output:

// Compile error: duplicate enum value name ACTIVE.
enum Status {
    STATUS_UNSPECIFIED = 0;
    STATUS_ACTIVE = 1;
    STATUS_INACTIVE = 2;
}
// With aliases:
enum Color {
    option allow_alias = true;
    COLOR_UNSPECIFIED = 0;
    COLOR_RED = 1;
    COLOR_ROJO = 1; // Alias: same value
}

Output:

// Go: Status_STATUS_ACTIVE, Status_STATUS_INACTIVE

Prevention

  • Prefix enum values with enum name (Go convention)
  • First value must be 0 (proto3 requirement)
  • Use *_UNSPECIFIED = 0 for zero value
  • Use allow_alias for value aliases
  • Use enum value = googles.PreserveUnknown for wire compatibility

Common Mistakes with proto enum

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What Go type does an enum generate?**

int32 with const values and a map for name/value lookup.

How to get enum name from value?

Status_name[int32(value)].

Can I use string enums?

Not natively. Use custom proto option or map in application code.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro