Go Proto Enum
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.
Right
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
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - 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
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