Rust中Protobuf使用詳解
Protobuf(Protocol Buffers)是 Google 推出的高效序列化協(xié)議;Rust中,prost 是最主流的 Protobuf 實(shí)現(xiàn),提供了編譯期代碼生成和運(yùn)行時(shí)序列化/反序列化能力。
工具與環(huán)境
必備工具:
- protoc:Protobuf 官方編譯器(負(fù)責(zé)解析
.proto文件) - prost:Rust 的 Protobuf 運(yùn)行時(shí)庫(kù)(提供序列化 / 反序列化邏輯)
- prost-build:Rust 的 Protobuf 編譯工具(集成
protoc,生成 Rust 代碼)
windows下protoc安裝(winget方式):
winget search protocwinget install Google.Protobufprotoc --version:# 輸出 libprotoc 33.0 或更高版本即可
項(xiàng)目中使用
配置Cargo.toml
添加prost與prost-build的依賴(lài),
[dependencies] prost = "0.14.1" [build-dependencies] prost-build = "0.14.1"
proto文件
在項(xiàng)目中添加proto/hello.proto文件:
syntax = "proto3";
package hello;
message MyMessage {
string name = 1;
int32 id = 2;
}build腳本
在項(xiàng)目根目錄添加build.rs用于把proto文件編譯為rs文件:
- out_dir:設(shè)定編譯rs文件存放位置(如"src/pb"下);
- compile_protos:編譯
- 第一個(gè)參數(shù)為要編譯proto文件(包含相對(duì)目錄);可以指定多個(gè)proto文件
- 第二個(gè)參數(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成功后,會(huì)在src/pb下創(chuàng)建hello.rs(與proto文件中的package名稱(chēng)相同)文件。
使用proto
生成rs文件后,即可使用:
- 通過(guò)include!宏,直接包含對(duì)應(yīng)rs文件
- 通過(guò)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使用簡(jiǎn)介的文章就介紹到這了,更多相關(guān)Rust Protobuf使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Rust 中引用模式與值模式的對(duì)比實(shí)踐指南
文章詳細(xì)介紹了Rust中的引用模式和值模式的區(qū)別,包括它們?cè)谒袡?quán)、生命周期、性能、內(nèi)存影響以及實(shí)際應(yīng)用中的選擇建議,通過(guò)對(duì)比和實(shí)際代碼示例,幫助讀者理解如何根據(jù)具體需求選擇合適的模式,從而寫(xiě)出高效且正確的Rust代碼,感興趣的朋友跟隨小編一起看看吧2025-11-11
vscode搭建rust開(kāi)發(fā)環(huán)境的圖文教程
Rust 是一種系統(tǒng)編程語(yǔ)言,它專(zhuān)注于內(nèi)存安全、并發(fā)和性能,本文主要介紹了vscode搭建rust開(kāi)發(fā)環(huán)境的圖文教程,具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03
Rust?連接?PostgreSQL?數(shù)據(jù)庫(kù)的詳細(xì)過(guò)程
這篇文章主要介紹了Rust?連接?PostgreSQL?數(shù)據(jù)庫(kù)的完整代碼,本文圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01
從入門(mén)到精通詳解Rust錯(cuò)誤處理完全指南
這篇文章主要為大家詳細(xì)介紹了Rust中錯(cuò)誤處理的相關(guān)方法和技巧,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一2025-12-12

