编译器通常将一个包含闭包的闭包实现为一个匿名结构体,该结构体包含了所有嵌套的闭包,以及它们所引用的变量。
下面是一个包含闭包的闭包的示例代码:
fn main() {
let a = 1;
let closure = || {
let b = 2;
let nested_closure = || {
println!("a: {}, b: {}", a, b);
};
nested_closure();
};
closure();
}
编译器将其翻译为:
struct Closure1<'a> {
a: &'a i32,
}
impl<'a> FnOnce<()> for Closure1<'a> {
type Output = ();
extern "rust-call" fn call_once(self, _: ()) -> Self::Output {
struct Closure2<'b, 'a> {
a: &'a i32,
b: &'b i32,
}
impl<'b, 'a> FnOnce<()> for Closure2<'b, 'a> {
type Output = ();
extern "rust-call" fn call_once(self, _: ()) -> Self::Output {
println!("a: {}, b: {}", self.a, self.b);
}
}
let b = 2;
let closure2 = Closure2 { a: self.a, b: &b };
closure2(())
}
}
fn main() {
let a = 1;
let closure1 = Closure1 { a: &a };
closure1(())
}
如上代码中所示,closure1
是一个包含闭包 Closure1
,它又包含了一个嵌套的闭包 Closure2
,Closure2
引用了变量 a
和 b
。编译器将 Closure1
翻译成一个结构体,它包含了 a
变量的引用。然后它实现了 FnOnce
trait,call_once
方法中