rust?中生成與使用protobuf的方法
首先創(chuàng)建一個(gè)項(xiàng)目proto
進(jìn)入到這個(gè)文件夾中 創(chuàng)建我們的proto文件
初始化的項(xiàng)目結(jié)構(gòu)是這個(gè)樣子的
新建一個(gè)hello.proto文件內(nèi)容如下
syntax = "proto3"; package hello; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
修改Cargo.toml文件 我們需要加一下 我們需要的依賴包
[package] name = "proto" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] prost = "0.7" prost-types = { version = "0.7", optional = true } [build-dependencies] prost-build = "0.7"
創(chuàng)建一個(gè)build.rs 編寫代碼如下:
fn main() { prost_build::Config::new() .out_dir("src/pb")//設(shè)置proto輸出目錄 .compile_protos(&["hello.proto"], &["."])//我們要處理的proto文件 .unwrap(); }
由于我們的項(xiàng)目中沒有pb的這個(gè)目錄 需要手動(dòng)創(chuàng)建一下,我們的整體結(jié)構(gòu)如下
然后運(yùn)行cargo build 結(jié)果如下
查看在我們剛剛創(chuàng)建的pb文件夾下是否有一個(gè)hello.rs文件
在pb目錄創(chuàng)建mod.rs文件 內(nèi)容如下
pub mod hello;
修改main.rs文件 內(nèi)容如下:
use pb::hello; mod pb; fn main() { let request = hello::HelloRequest { name: "world".to_string(), }; println!("request: {:?}", request); }
執(zhí)行cargo run
到此這篇關(guān)于rust 中protobuf生成與使用的文章就介紹到這了,更多相關(guān)rust 使用protobuf內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Rust個(gè)人學(xué)習(xí)小結(jié)之Rust的循環(huán)
這篇文章主要介紹了Rust個(gè)人學(xué)習(xí)小結(jié)之Rust的循環(huán),今天主要了解了Rust語言的3種循環(huán)方法:?loop、while、for,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01Rust中的Cargo構(gòu)建、運(yùn)行、調(diào)試
Cargo是rustup安裝后自帶的,Cargo?是?Rust?的構(gòu)建系統(tǒng)和包管理器,這篇文章主要介紹了Rust之Cargo構(gòu)建、運(yùn)行、調(diào)試,需要的朋友可以參考下2022-09-09rust實(shí)現(xiàn)post小程序(完整代碼)
這篇文章主要介紹了rust實(shí)現(xiàn)一個(gè)post小程序,本文通過示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-04-04