gpt4 book ai didi

rust - 移动关闭的特征?

转载 作者:行者123 更新时间:2023-12-03 11:41:01 26 4
gpt4 key购买 nike

有没有办法区分move来自非 move 的关闭使用 Rust 中的特征绑定(bind)的闭包?
对于上下文,我在我的程序中使用盒装闭包(Box + dyn Fn 特征),所以我需要担心生命周期,因为 IIUC 这些闭包可能会引用堆栈。
我想知道我是否可以限制为盒装move -闭包只是为了(希望)我可以避免处理生命周期,因为在这种情况下这些很快就会变得困惑。
还是有其他更好、更惯用的方法来达到同样的效果?

最佳答案

Is there a way to distinguish move closures from non-move closures using a trait bound in Rust?


“移动”在这里是一个红鲱鱼。您可以在闭包中通过引用借用变量,也可以 移动对闭包的引用,它们等价地相同。例子:
fn takes_closure<'a>(_closure: &'a dyn Fn() -> &'a i32) {}

fn main() {
let value = 123;
let value_ref = &value;

// captures value by borrowing it by reference
takes_closure(&|| &value);

// captures value_ref by moving it
takes_closure(& move || value_ref);

// what's the difference between the above 2 cases?
// answer: there isn't any
}

I'm using boxed closures in my program so I need to worry about lifetimes since IIUC these closures may reference the stack.


不,默认情况下,盒装闭包得到一个隐含的 'static边界。除非您明确设置自己的生命周期界限,否则您不能在盒装闭包中借用堆栈变量。
From Default trait object lifetimes in The Rust Reference :

If the trait has no lifetime bounds, then the lifetime is inferred in expressions and is 'static outside of expressions.


例如,仅此函数签名就保证返回的闭包不会捕获任何非 'static外部引用或变量:
fn returns_boxed_closure() -> Box<dyn Fn()>;
// full desugared return type: Box<dyn Fn() + 'static>
如上所述,如果您希望盒装闭包不受 'static 的限制生命周期,否则您必须明确注释它。这是一个例子:
fn returns_boxed_closure<'a, T>(reference: &'a T) -> Box<dyn Fn() + 'a> {
Box::new(move || drop(reference))
}
上面的例子特别好,因为它显示即使你使用 移动关键字,您仍然可以使用它来创建带有非 'static 的盒装闭包。生命周期。
无论如何,简而言之:你不需要做任何特别的事情,盒装的闭包会得到一个隐含的 'static默认绑定(bind)并按照您希望的方式工作,即您不必担心生命周期。

关于rust - 移动关闭的特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65296603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com