Rust语言

关注公众号 jb51net

关闭
首页 > 软件编程 > Rust语言 > Rust Protobuf使用

Rust中Protobuf使用详解

作者:alwaysrun

本文介绍了如何在Rust中使用Protobuf进行序列化和反序列化,并介绍了如何在项目中使用生成的Rust代码,通过include!宏和mod.rs文件的配置,可以方便地在Rust项目中使用Protobuf,感兴趣的朋友跟随小编一起看看吧

Protobuf(Protocol Buffers)是 Google 推出的高效序列化协议;Rust中,prost 是最主流的 Protobuf 实现,提供了编译期代码生成和运行时序列化/反序列化能力。

工具与环境

必备工具:

windows下protoc安装(winget方式):

  1. winget search protoc
  2. winget install Google.Protobuf
  3. protoc --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文件:

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下创建hello.rs(与proto文件中的package名称相同)文件。

使用proto

生成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);
}

到此这篇关于Rust中Protobuf使用简介的文章就介绍到这了,更多相关Rust Protobuf使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文