vector - 是否可以在 protobuf 消息中包含向量字段以生成 Rust 结构?

标签 vector rust protocol-buffers proto3

我有一个用于在项目中生成类型的 protobuf 文件。其中一种类型如下所示:

syntax = "proto3";

// ...

message myStruct {
    int32 obj_id = 1;
    string obj_code = 2;
    string obj_name = 3;
    // ... some more fields
}
// ... some more message, enum, etc ....

然后我可以启动一个小脚本,它通过 protoc-gen-go 生成一些 Go 代码,稍后通过另一个使用 protoc-gen-rust 的脚本转换为 Rust >。

结果是一个如下所示的 Rust 文件:

// This file is generated by rust-protobuf 2.0.0. Do not edit
// @generated

// ...

pub struct myStruct {
    // message fields
    pub obj_id: i32,
    pub obj_code: ::std::string::String,
    pub obj_name: ::std::string::String,
    // ... some more fields
}
impl myStruct {
    // ... lots of constructors, getters, setters, etc
}

我不想要一个更好的方法来完全生成 Rust 类型,这个项目很大并且正在生产中,我的工作不是重写/重组它而是添加一些功能,为此我需要一些不错的小东西要添加到几个结构中的标志向量。

我想在 myStruct 结构中添加一些 Vec 字段,例如:

pub struct myClass {
    // ... some fields like obj_id etc ...

    // the fields I want to add
    bool_vec: Vec<bool>,
    bool_vec_vec: Vec<Vec<bool>>,
    // ...
}

是否可以使用 proto-buf 来做到这一点?如果是,我该怎么做?

最佳答案

你可以使用 protobuf repeated fields :

repeated: this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.

喜欢:

message bool_vec{
    repeated bool element = 1;
}
message bool_vec_vec{
    repeated bool_vec element = 1;
}
message myStruct {
    ...
    bool_vec v = 100;
    bool_vec_vec vv = 101;
    ...
}

documentation of RepeatedField来自 protobuf C++ 库(代表重复字段,如此处重复的 bool)表明它具有我们对向量的期望:通过索引和迭代器访问。您生成的代码也可以通过索引访问和添加/删除最后的方法。

关于vector - 是否可以在 protobuf 消息中包含向量字段以生成 Rust 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759398/

相关文章:

c++ - 如何搜索 vector 元素并替换它?

c++ - 如何维护对 std::priority_queue 容器的引用?

pointers - 如何在 Rust 中安全地构建指向 LV2 原子 DST 的胖指针/指针?

protocol-buffers - gRPC 中的异常处理

java - 我无法从 wales-latest.osm.pbf 文件中提取 border_type=city

c++ - 不能推 GlDouble vector 的 vector 吗?

rust - 在非阻塞模式下使用带有 rust-portaudio 的特征类型

for-loop - 简化迭代循环(使用 crate )

android - 将 ProtoBuf 对象存储在 SharedPreferences 中

c++ - 转换为唯一基类指针的 vector