0

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

I'm using protoc-rust to procedurally generate Rust code from protocol buffers. In particular, it generates structs and methods for the messages defined in the protos. I need to add new members to these structs to initialize some WebAssembly::Instances off of a bytes object in the struct

The struct:

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,
}

What I want to do:

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()
    }

}

What I get:

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

0

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

Rust does not allow that.

What you can do is define another struct:

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

.. and return it from your init function.

Nickolay
  • 31,095
  • 13
  • 107
  • 185
  • That would work but it seems a little messy. The struct is being generated via a build.rs invocation of protoc-rust. It would be nice to dynamically change the source files generated, before the main compilation so that the definition is added prior to compile time. (Ie. also in the build.rs) – Samuel Warfield Jul 29 '19 at 23:37
  • If you're looking for a way to ask `protoc-rust` to do this, perhaps mentioning it in the summary would help the right people see this question? – Nickolay Jul 29 '19 at 23:43
  • That's certainly an option thats better than hard coding a line insertion, The best solution would be a lib that could parse rust code and dynamically find the struct by name and do the insertion – Samuel Warfield Jul 29 '19 at 23:53