Use the prost crate to compile .proto files into Rust structs and then serialize/deserialize data using the generated methods.
- Add
prostandprost-buildto yourCargo.tomldependencies.
[dependencies]
prost = "0.13"
[build-dependencies]
prost-build = "0.13"
- Create a
build.rsfile to compile your.protofiles during the build process.
fn main() {
prost_build::compile_protos(&["src/message.proto"], &["src/"]).unwrap();
}
- Define your message structure in
src/message.proto.
syntax = "proto3";
message Message {
string content = 1;
}
- Import the generated module in your
src/lib.rsorsrc/main.rsto 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);
}
- Run
cargo buildto compile the proto files and your application.
cargo build
- Execute your binary to verify serialization and deserialization work correctly.
cargo run