我可以在闭包中通过引用捕获某些内容,而通过值捕获其他内容吗?

假设我们有以下代码,我在其中定义了一个名为closure. 在这个闭包中,我想x通过不可变引用 ( &T)来使用外部,同时,y通过获取所有权来使用。我怎样才能做到这一点?如果我使用move,闭包中使用的所有外部变量都将移动到闭包中。而且这里的外部变量y是可复制的。

let x: i32 = 1;
let y: i32 = 2;
let closure = || {
    println!("{}", x);  // make sure x is used by &T.
    // println!("{}", y);  // how can I use y by taking its ownership?
};
closure();

回答

请注意,通过移动引用进行捕获等同于通过引用进行捕获。

当您move向闭包添加关键字时,是的,所有内容都通过移动捕获。但是你可以移动一个引用,这就是没有move关键字的闭包所做的。

let x: i32 = 1;
let y: i32 = 2;
let closure = {
    let x = &x;
    move || {
        println!("{}", x);  // borrowing (outer) x
        println!("{}", y);  // taking the ownership of y
    }
};
closure();

  • Another useful idiom is to open a scope to create the closure, and use `let x = &x` to force borrowing in an otherwise `move` closure: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9e241b2b4394dcdcb715c9ef4bdba919

以上是我可以在闭包中通过引用捕获某些内容,而通过值捕获其他内容吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>