Skip to content

Go Proto Message Types

DodaTech 2 min read

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

Protobuf field types -- Map protobuf types to Go types correctly to avoid unexpected generated code.

The Problem

Protobuf types don't always map 1:1 to Go. int32 -> int32, int64 -> int64, string -> string, but uint64 -> uint64, sint64 -> int64 with zigzag encoding.

Wrong

syntax = "proto3";
message User {
    int32 age = 1;       // Go: int32
    string name = 2;     // Go: string
    uint64 id = 3;       // Go: uint64
    double score = 4;    // Go: float64
    float ratio = 5;     // Go: float32
    bytes data = 6;      // Go: []byte
    bool active = 7;     // Go: bool
    Status status = 8;   // Go: enum
    map<string, string> meta = 9; // Go: map[string]string
}

Output:

// Generated Go types match proto types
message Event {
    int64 timestamp = 1 [(gogoproto.casttype) = "time.Time"];
}

Output:

// Custom types via protobuf options

Prevention

  • Use int32 for small numbers, int64 for large
  • Use sint32/sint64 for negative numbers (more efficient)
  • Use uint32/uint64 for unsigned
  • Use fixed32/fixed64 for fixed-size fields (faster but larger)
  • Use string for UTF-8 text, bytes for binary data

Common Mistakes with proto message types

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

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 is the difference between int32 and sint32?**

int32 uses variable-length encoding. sint32 uses zigzag encoding (more efficient for negative numbers).

What Go type does bool generate?

bool. Default is false.

How to handle large numbers in Go?

Use google.protobuf.Int64Value wrapper for nullable int64.


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