Rust中Protobuf使用詳解
Protobuf(Protocol Buffers)是 Google 推出的高效序列化協(xié)議;Rust中,prost 是最主流的 Protobuf 實現(xiàn),提供了編譯期代碼生成和運行時序列化/反序列化能力。
工具與環(huán)境
必備工具:
- 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:編譯
- 第一個參數(shù)為要編譯proto文件(包含相對目錄);可以指定多個proto文件
- 第二個參數(shù)proto所在路徑
use prost_build;
fn main() {
println!("cargo:rerun-if-changed=hello.proto");
// try create the output folder
std::fs::create_dir_all("src/pb").expect("Failed to create output directory");
// compile the proto file
prost_build::Config::new()
.out_dir("src/pb")
.compile_protos(&["proto/hello.proto"], &["proto/"])
.expect("Failed to compile proto files");
}build成功后,會在src/pb下創(chuàng)建hello.rs(與proto文件中的package名稱相同)文件。
使用proto
生成rs文件后,即可使用:
- 通過include!宏,直接包含對應rs文件
- 通過use引入
- 在pb下創(chuàng)建mod.rs,并添加
pub mod hello; - 在main中引入:
mod pb; use pb::hello::MyMessage;
- 在pb下創(chuàng)建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);
}到此這篇關(guān)于Rust中Protobuf使用簡介的文章就介紹到這了,更多相關(guān)Rust Protobuf使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vscode搭建rust開發(fā)環(huán)境的圖文教程
Rust 是一種系統(tǒng)編程語言,它專注于內(nèi)存安全、并發(fā)和性能,本文主要介紹了vscode搭建rust開發(fā)環(huán)境的圖文教程,具有一定的參考價值,感興趣的可以了解一下2024-03-03
Rust?連接?PostgreSQL?數(shù)據(jù)庫的詳細過程
這篇文章主要介紹了Rust?連接?PostgreSQL?數(shù)據(jù)庫的完整代碼,本文圖文實例代碼相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-01-01

