How to Work with Protocol Buffers in Rust (prost)

Use the prost crate to compile .proto definitions into Rust code for efficient data serialization and deserialization.

Use the prost crate to compile .proto files into Rust structs and then serialize/deserialize data using the generated methods.

  1. Add prost and prost-build to your Cargo.toml dependencies.
[dependencies]
prost = "0.13"

[build-dependencies]
prost-build = "0.13"
  1. Create a build.rs file to compile your .proto files during the build process.
fn main() {
    prost_build::compile_protos(&["src/message.proto"], &["src/"]).unwrap();
}
  1. Define your message structure in src/message.proto.
syntax = "proto3";

message Message {
    string content = 1;
}
  1. Import the generated module in your src/lib.rs or src/main.rs to use the types.
mod message {
    include!(concat!(env!("OUT_DIR"), "/message.rs"));
}

use message::Message;

fn main() {
    let msg = Message { content: "Hello".to_string() };
    let data = msg.encode_to_vec();
    let decoded = Message::decode(&data[..]).unwrap();
    println!("Decoded: {}", decoded.content);
}
  1. Run cargo build to compile the proto files and your application.
cargo build
  1. Execute your binary to verify serialization and deserialization work correctly.
cargo run