我在理解闭包方面遇到了一些困难,所以我跳到一个论坛上询问一些有关幕后情况的问题。有人给我举了这样一个例子:
对于以下代码:
Run Code Online (Sandbox Code Playgroud)let x = String::new(); let f = || { println!("{x}") }; f();下面的代码是 Rust 在后台生成的(这只是一个近似值,它并没有真正运行):
Run Code Online (Sandbox Code Playgroud)struct UnnameableClosureType<'a> { x0: &'a String, } impl<'a> Fn<()> for UnnameableClosureType<'a> { type Output = (); extern "rust-call" fn call(&self, args: Args) -> Self::Output { println!("{}", self.x0); } } impl<'a> FnMut<()> for UnnameableClosureType<'a> { type Output = (); extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output { self.call(args) } } impl<'a> FnOnce<()> for UnnameableClosureType<'a> { type Output = (); extern "rust-call" fn …