在 Rust 中分配字段之前从闭包访问 Impl 字段?



我是Rust的新手,这可能是显而易见的。

基本上,我有一个场景,你可以在下面看到,我创建了一个新的类型,其中添加了一个闭包,但这个闭包需要访问尚未创建的数据。数据将在调用闭包时创建,但在最初创建闭包时,数据还不可用。

最好的处理方式是什么?

我也很好奇,如果我的闭包不是闭包,而是实现中的一个私有函数,我将如何访问这些数据?这个闭包/函数是WasmTime的回调,需要一个显式的方法签名,这不允许我向其中添加$self。那么,如果函数参数中没有引用$self,我怎么能获得实现的实例字段呢?

pub struct EmWasmNode {
wasmStore: Store<WasiCtx>,
wasmTable: Table,
}
impl EmWasmNode {
pub fn new(filePath: &str) -> Result<Self> {
let engine = Engine::default();
// let module = Module::from_file(&engine, "wasm/index.wast")?;
let module = Module::from_file(&engine, filePath)?;
let mut linker = Linker::new(&engine);
wasmtime_wasi::add_to_linker(&mut linker, |s| s)?;
let wasi = WasiCtxBuilder::new()
.inherit_stdio()
.inherit_args()?
.build();
let mut store = Store::new(&engine, wasi);
linker.func_wrap("env", "emscripten_set_main_loop", |p0: i32, p1: i32, p2: i32| {
println!("emscripten_set_main_loop {} {} {}", p0, p1, p2);
/*** How would I access wasmTable and wasmStore from here to execute more methods??? ***/
//let browserIterationFuncOption:Option<wasmtime::Val> = Self::wasmTable.get(&mut Self::wasmStore, p0 as u32);
// browserIterationFuncOption.unwrap().unwrap_funcref().call(&store, ());
})?;
let instance = linker.instantiate(&mut store, &module)?;
let table = instance
.get_export(&mut store, "__indirect_function_table")
.as_ref()
.and_then(extern_table)
.cloned();
let start = instance.get_typed_func::<(), (), _>(&mut store, "_start")?;
start.call(&mut store, ())?;
Ok(EmWasmNode {
wasmStore: store,
wasmTable: table.unwrap(),
})
}

之前必须实例化一个结构。我建议使用下面更简单的代码来查看我的想法。

struct Atype
{
name: String,
}
impl Atype
{
pub fn new() -> Self
{
Self{ name: String::from("zeppi")}
}

pub fn test(&self) -> ()
{
let func = | x | { println!("{} {}", &self.name, x);};
func(3)
}
}
fn main() {
let o = Atype::new();
o.test();
}

最新更新