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

Is it possible to include vector fields in a protobuf message to generate Rust struct?

我有一个用于在项目中生成类型的 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 类型,该项目庞大且正在生产中,我的工作不是 rewrite/reorganize 它只是添加一些功能,为此我需要在几个结构中添加一些漂亮的小标志向量。

我想在 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;
    ...
}

protobuf C++ 库中的 documentation of RepeatedField(表示重复字段,如此处重复的 bool)表明它具有我们对向量的期望:通过索引和迭代器访问。您生成的代码也可以通过索引和 add/remove 最后一种方法进行访问。