Rust中Protobuf使用简介
Protobuf(Protocol Buffers)是 Google 推出的高效序列化协议;Rust中,prost 是最主流的 Protobuf 实现,提供了编译期代码生成和运行时序列化/反序列化能力。
工具与环境
必备工具:
- protoc:Protobuf 官方编译器(负责解析
.proto文件) - prost:Rust 的 Protobuf 运行时库(提供序列化 / 反序列化逻辑)
- prost-build:Rust 的 Protobuf 编译工具(集成
protoc,生成 Rust 代码)
windows下protoc安装(winget方式):
winget search protocwinget install Google.Protobufprotoc --version:# 输出 libprotoc 33.0 或更高版本即可
项目中使用
配置Cargo.toml
添加prost与prost-build的依赖,
[dependencies]
prost = "0.14.1"[build-dependencies]
prost-build = "0.14.1"
proto文件
在项目中添加proto/hello.proto文件:
syntax = "proto3";package hello;message MyMessage {string name = 1;int32 id = 2;
}
build脚本
在项目根目录添加build.rs用于把proto文件编译为rs文件:
- out_dir:设定编译rs文件存放位置(如"src/pb"下);
- compile_protos:编译
- 第一个参数为要编译proto文件(包含相对目录);可以指定多个proto文件
- 第二个参数proto所在路径
use prost_build;fn main() {println!("cargo:rerun-if-changed=hello.proto");// try create the output folderstd::fs::create_dir_all("src/pb").expect("Failed to create output directory");// compile the proto fileprost_build::Config::new().out_dir("src/pb").compile_protos(&["proto/hello.proto"], &["proto/"]).expect("Failed to compile proto files");
}
build成功后,会在src/pb下创建hello.rs(与proto文件中的package名称相同)文件。
使用proto
生成rs文件后,即可使用:
- 通过include!宏,直接包含对应rs文件
- 通过use引入
- 在pb下创建mod.rs,并添加
pub mod hello; - 在main中引入:
mod pb; use pb::hello::MyMessage;
- 在pb下创建mod.rs,并添加
// include!("pb/hello.rs");
mod pb;
use pb::hello::MyMessage;use prost::Message;fn main() {let msg = MyMessage {name: "Protobuff example".to_string(),id: 123,};let encoded = msg.encode_to_vec();println!("Encoded Msg: {:?}", encoded);let decoded = MyMessage::decode(&encoded[..]).unwrap();println!("Decoded Msg: {:?}", decoded);
}
