小编Ano*_*non的帖子

我得到的这个解释(幕后的 Rust 代码需要在调用时消耗变量)正确吗?

我在理解闭包方面遇到了一些困难,所以我跳到一个论坛上询问一些有关幕后情况的问题。有人给我举了这样一个例子:

对于以下代码:

let x = String::new();
let f = || { println!("{x}") };
f();
Run Code Online (Sandbox Code Playgroud)

下面的代码是 Rust 在后台生成的(这只是一个近似值,它并没有真正运行):

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 …
Run Code Online (Sandbox Code Playgroud)

struct closures rust

0
推荐指数
1
解决办法
78
查看次数

标签 统计

closures ×1

rust ×1

struct ×1