繁体   English   中英

如何将生存期参数添加到闭包而不返回引用

[英]How to add lifetime argument to closure not returning a reference

假设您有一个函数返回一个对引用起作用的闭包。 当然,引用后面的对象必须至少生存到调用该闭包的时间。

这里有一个非常简单的例子,说明了这个问题。

fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct {
    || {obj.clone()}
}

编译器指出返回的闭包具有生命周期静态值

无法推断适当的寿命
...但是这借... rustc
main.rs(60,56):此返回类型的计算结果为'static寿命...
main.rs(61,5):...但是这借...

我如何告诉编译器,只要引用有效,我就只使用函数(闭包)的结果?

谢谢!

[编辑]

您是否需要一个既保留引用又包含闭包的伪结构?

struct Dummy<'a>{
  reference: &'a MyStruct,
  closure: Fn() -> MyStruct
}

假设克隆的成本很高,并且可能永远不会调用闭包。 ->懒惰评估是必须的。

编译器告诉您该怎么做:

error: cannot infer an appropriate lifetime
 --> src/lib.rs:2:9
  |
1 | fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct {
  |                                         --------------------- this return type evaluates to the `'static` lifetime...
2 |         || {obj.clone()}
  |         ^^^^^^^^^^^^^^^^ ...but this borrow...
  |
note: ...can't outlive the lifetime 'a as defined on the function body at 1:15
 --> src/lib.rs:1:15
  |
1 | fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct {
  |               ^^
help: you can add a constraint to the return type to make it last less than `'static` and match the lifetime 'a as defined on the function body at 1:15
  |
1 | fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct + 'a {
  |                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^

您需要在返回类型上添加+ 'a 然后,编译器将告诉您缺少move ,但是在修复该错误之后, 您的代码可以正常工作

fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct + 'a {
    || {obj.clone()}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM