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:設(shè)定編譯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)文章
Rust語言從入門到精通系列之Iterator迭代器深入詳解
這篇文章主要為大家介紹了Rust語言從入門到精通系列之Iterator迭代器深入詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
Rust使用Sled添加高性能嵌入式數(shù)據(jù)庫
這篇文章主要為大家詳細介紹了如何在Rust項目中使用Sled庫,一個為Rust生態(tài)設(shè)計的現(xiàn)代、高性能嵌入式數(shù)據(jù)庫,感興趣的小伙伴可以跟隨小編一起學習一下2024-03-03
Rust實現(xiàn)構(gòu)建器模式和如何使用Bon庫中的構(gòu)建器
這篇文章主要介紹了Rust實現(xiàn)構(gòu)建器模式和如何使用Bon庫中的構(gòu)建器,本文給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-08-08
關(guān)于Rust編譯時報link.exe?not?found錯誤問題
這篇文章主要介紹了Rust編譯的時候報出link.exe?not?found錯誤問題,解決方法是在命令行就是CMD執(zhí)行相應的命令即可,本文給大家分解決方法,需要的朋友可以參考下2022-09-09

