rust - 向结构体添加新的成员变量

标签 rust

<分区>

我正在尝试将新成员变量添加到 impl block 中的结构。

我正在使用 protoc-rust从 Protocol Buffer 程序化地生成 Rust 代码。特别是,它为原型(prototype)中定义的消息生成结构和方法。我需要向这些结构添加新成员以初始化结构中字节对象的一些 WebAssembly::Instance

结构:

pub struct Module {
    // message fields
    pub module_name: ::std::string::String,
    pub init_script: ::std::string::String,
    pub JS_boiler_plate: ::std::string::String,
    pub functions: ::protobuf::RepeatedField<Function>,
    pub meta_data: ::std::string::String,
    pub packager: ::std::string::String,
    pub pure_wasm: bool,
    pub wasm_binary: ::std::vec::Vec<u8>,
    // special fields
    pub unknown_fields: ::protobuf::UnknownFields,
    pub cached_size: ::protobuf::CachedSize,
}

我想做的事情:

impl RPC_Module::Module {
    self.wasm_instance: WebAssembly::Instance;

    pub fn init(&mut self) -> Result<(), &'static str> {
        // Init the instance based off of wasm_binary
        let self.wasm_instance = WebAssembly::Instance::new()
    }

}

我得到的:

Compiling wRPC v0.1.0 (/Users/swarfield/Code/wRPC-Core/w-rpc-core)
error: expected one of `async`, `const`, `crate`, `default`, `existential`, `extern`, `fn`, `pub`, `type`, `unsafe`, or `}`, found `let`
  --> src/protos/mod.rs:12:5
   |
11 | impl RPC_Module::Module {
   |                          - expected one of 11 possible tokens here
12 |     let self.wasm_instance: WebAssembly::Instance;
   |     ^^^ unexpected token

最佳答案

I'm trying to add new member variables to a struct in an impl block.

Rust 不允许这样做。

你可以做的是定义另一个结构:

struct ModuleInstance {
    wasm_instance: WebAssembly::Instance,
    module: RPC_Module::Module
}

.. 并从您的 init 函数返回它。

关于rust - 向结构体添加新的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57262376/

相关文章:

rust - 如何使用跟踪订阅者设置自定义时间戳格式?

rust - 如何使用 serde_json 序列化 std::env:vars()?

rust - 结果<T, E> 输入 Rust。为什么引用不能作为 T 或 E 传递?

rust - 如何访问元组变量索引处的元素?

rust - 如何将空字符串解析为 None?

postgresql - 尝试使用 Diesel 插入值时出现 "expected struct String, found struct schema::my_table::columns::my_column"

web-applications - 在 rust 中使用扭曲来服务静态文件

naming - 为什么叫它 "Rust"?

syntax - 是否有在相似结构之间移动字段的语法?

rust - Rust:创建结构,借入/生命周期问题的向量时为E0597