rust使用protobuf

前言

c++,java,go 等直接是用 ,具体就不说了,这章主要讲述rust 使用protobuf
rust使用protobuf_第1张图片

这章主要讲述2种
1 > protoc + protoc-gen-rust plugin
2> protoc + prost-build
rust使用protobuf_第2张图片

1:环境
win10
rustrover64
25-2 下载地址 https://github.com/protocolbuffers/protobuf/releases
25-2 是rust 实验性的
纯粹用这个 出错了,这里先不讨论了,由解决的麻烦留个言我
在这里插入图片描述

3.3.0 golang编译的
rust使用protobuf_第3张图片

在这里插入图片描述
rust使用protobuf_第4张图片
2:安装 测试
rust使用protobuf_第5张图片
1> protoc + protoc-gen-rust plugin
安装插件
cargo install protobuf-codegen 生成protoc-gen-rust
或 用源码生成

执行
protoc --rust_out=. *.proto
生成
在这里插入图片描述
编译测试
toml 增加
[dependencies]
protobuf=“3.3”
rust使用protobuf_第6张图片

2>protoc + prost-build
[dependencies]
prost=“0.12”
prost-types = “0.12”

[build-dependencies]
prost-build = { version = “0.12”}#,features = [“cleanup-markdown”]

rust使用protobuf_第7张图片

build.rs 从网上抄来的

use std::process::Command;

fn main() {
    //std::env::set_var("PROTOC", protobuf_src::protoc());
    //不增加下面一句 老是提示没权限,所以直接把环境变量写到这里
    std::env::set_var("PROTOC", "E:/work/protobuf/protobuf_proto/protoc"); //protoc_25_2 
    let mut config = prost_build::Config::new();
    config.bytes(&["."]);
    // 表示给生成的数据结构加上额外的trait,比如这里的: PartialOrd,表示对象实现排序trait
    config.type_attribute(".", "#[derive(PartialOrd)]");  //如果去掉这个比较属性,就没上面的比较重复的问题了
    config
        .out_dir("src/pb") //指定输出的目录
        .compile_protos(&["chat.proto"], &["."]) // 列举需要编译的文件
        .unwrap();

    // 下面表示调用系统cargo命令,并使用fmt进行标准代码格式化
    Command::new("cargo")
        .args(&["fmt", "--", "src/*.rs"])
        .status()
        .expect("cargo fmt failed");

    println!("proto files build finish.");
}

一个重复错误,手动修改下(因为加了 config.type_attribute(“.”, “#[derive(PartialOrd)]”); 这句,这个地方重复了)
rust使用protobuf_第8张图片
编译运行
rust使用protobuf_第9张图片
3:2种proto生成的 rs内容真不一样
rust使用protobuf_第10张图片
4:DEMO工程 后续如有需要再上传
如果觉得有用,麻烦点个赞,加个收藏

你可能感兴趣的:(杂项,rust,学习,rust,后端,protobuf)