[英]Is it possible to include vector fields in a protobuf message to generate Rust struct?
I have a protobuf file used to generate types in a project. 我有一个protobuf文件,用于在项目中生成类型。 One of the types looks like:
其中一种类型如下所示:
syntax = "proto3";
// ...
message myStruct {
int32 obj_id = 1;
string obj_code = 2;
string obj_name = 3;
// ... some more fields
}
// ... some more message, enum, etc ....
Then I can launch a tiny script that generates some Go code though protoc-gen-go
, that gets later translated into Rust though another script using protoc-gen-rust
. 然后,我可以启动一个微型脚本,该脚本通过
protoc-gen-go
生成一些Go代码,然后通过另一个使用protoc-gen-rust
脚本将其翻译成Rust。
The result is a Rust file that looks like: 结果是一个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
}
I don't want a better way to do generate the Rust types altogether, the project is massive and in prod, my job is not to rewrite/reorganize it but just to add some functionalities, for which I need some nice little vectors of flags to be added in a couple of structures. 我不希望有更好的方法来完全生成Rust类型,该项目非常庞大且生产中,我的工作不是重写/重组它,而只是添加一些功能,为此我需要一些漂亮的标志向量被添加到几个结构中。
I'd like to add some Vec
fields in the myStruct
struct, like those: 我想在
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>>,
// ...
}
Is it possible to do so using the proto-buf thing, or not? 是否可以使用原始缓冲东西来做到这一点? If yes, how can I do it?
如果是,我该怎么办?
You could use protobuf repeated fields : 您可以使用protobuf重复字段 :
repeated
: this field can be repeated any number of times (including zero) in a well-formed message.repeated
:在格式正确的消息中,此字段可以重复任意次(包括零次)。 The order of the repeated values will be preserved.重复值的顺序将保留。
Like: 喜欢:
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;
...
}
The documentation of RepeatedField
from the protobuf C++ library (which represents repeated fields like the repeated bool
here) shows that it has what we would expect from vectors: access by index and iterators. 该的文档
RepeatedField
从protobuf的C ++库(代表重复像重复的域bool
这里)表明,它是我们所期望的载体:通过索引和迭代器访问。 Your generated code will also have access by index and add/remove last methods. 您生成的代码也可以按索引访问,并添加/删除最后一个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.