4.35-dev) provides the protobuf crate for message manipulation and the protobuf-codegen crate for generating Rust code from .proto files at build time.
Installation
Add the codegen build dependency
Code generation is performed in a
build.rs build script using protobuf-codegen:Get a compatible protoc binary
The version of
protoc must match the protobuf crate version you use: if you use Rust protobuf x.y.z, use protoc version y.z. Download a prebuilt binary from the releases page and add it to your $PATH.Generating code
Create abuild.rs at the root of your crate that runs protobuf-codegen during compilation:
main.rs or lib.rs:
Working with messages
Creating messages with the proto! macro
The proto! macro provides a concise syntax for constructing messages with nested fields:
Accessing fields
Generated accessor methods are nil-safe and return default values for unset fields:Serializing and deserializing
Well-known types
Theprotobuf-well-known-types crate provides Rust types for Timestamp, Duration, Struct, Any, and other standard well-known types:
Version compatibility
Key API reference
proto! macro
Concise message construction with struct-like syntax. Use
__ for nested message literals. Supports repeated fields via array syntax.Message trait
write_to_bytes() / parse_from_bytes(&[u8]) for binary serialization. write_to_writer(W) / parse_from_reader(R) for streaming I/O.Field accessors
Generated
name(), id(), etc. methods return values or references. For optional fields, use has_field() to check presence before accessing.protobuf-codegen
Build-time code generator. Configure via
CodeGen::new().inputs([...]).include("proto").generate_and_compile().