【问题标题】:Is it possible to include vector fields in a protobuf message to generate Rust struct?是否可以在 protobuf 消息中包含向量字段以生成 Rust 结构?
【发布时间】:2019-04-19 09:12:41
【问题描述】:

我有一个用于在项目中生成类型的 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 来做到这一点?如果是,我该怎么做?

【问题讨论】:

    标签: vector rust protocol-buffers proto3


    【解决方案1】:

    你可以使用protobuf repeated fields:

    repeated:该字段可以在格式良好的消息中重复任意次数(包括零次)。重复值的顺序将被保留。

    喜欢:

    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)表明它具有我们对向量的期望:通过索引和迭代器访问。您生成的代码也可以通过索引访问和添加/删除最后一个方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 2012-06-29
      • 2021-07-18
      • 2022-11-23
      • 1970-01-01
      • 2018-03-09
      • 2018-09-12
      相关资源
      最近更新 更多