【问题标题】:How do I apply a macro attribute to a function defined in a separate module?如何将宏属性应用于单独模块中定义的函数?
【发布时间】:2018-11-18 18:11:06
【问题描述】:

我有兴趣通过rust-webpack-template 使用wasm-bindgen 将Rust 代码编译为WebAssembly。但是,我想避免直接用#[wasm_bindgen] 属性宏直接包装我的代码,这样我就可以从生成的WebAssembly 接口中分离出功能逻辑,从而更好地组织我的项目。相反,我希望将绑定生成放在单独的文件中,例如:

mod my_code;
use my_code::my_function;

#[wasm_bindgen]
my_function; // I want to do something like this!

我知道#[wasm_bindgen] 是一个宏属性,它对通常遵循的函数定义的 AST 进行操作,但是有没有一种方法可以将该宏应用于其他地方定义的代码?

【问题讨论】:

    标签: rust rust-macros wasm-bindgen


    【解决方案1】:

    据我所知,没有办法做到这一点。宏对其所附加的代码的 AST 进行操作,这里没有要附加的代码。

    如果你真的需要这个,你必须复制并粘贴你的函数的签名:

    mod my_code {
        pub fn my_function(_: i32) -> String {
            unimplemented!()
        }
    }
    
    #[wasm_bindgen]
    fn my_function(a: i32) -> String {
        my_code::my_function(a)
    }
    

    您可以编写一个宏来使包装稍微不那么乏味,但您仍然需要复制函数名称、参数类型和返回类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 2020-11-22
      • 1970-01-01
      • 2016-08-21
      • 2012-04-15
      • 1970-01-01
      相关资源
      最近更新 更多