如何将生命周期参数添加到不返回引用的闭包
How to add lifetime argument to closure not returning a reference
假设您有一个函数返回一个对引用起作用的闭包。
当然,引用后面的对象必须至少在闭包被调用时存在。
这是一个非常简单的例子,它演示了问题。
fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct {
|| {obj.clone()}
}
编译器指出返回的闭包具有生命周期static:
cannot infer an appropriate lifetime
...but this borrow...rustc
main.rs(60, 56): this return type evaluates to the 'static
lifetime...
main.rs(61, 5): ...but this borrow...
如何告诉编译器只要引用有效我就只使用函数的结果(闭包)?
谢谢!
[编辑]
您是否需要一个包含引用和闭包的虚拟结构?
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 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
您需要在 return 类型上添加 + 'a
。然后编译器会告诉你你缺少 move
,但修复后,your code works:
fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct + 'a {
|| {obj.clone()}
}
假设您有一个函数返回一个对引用起作用的闭包。 当然,引用后面的对象必须至少在闭包被调用时存在。
这是一个非常简单的例子,它演示了问题。
fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct {
|| {obj.clone()}
}
编译器指出返回的闭包具有生命周期static:
cannot infer an appropriate lifetime
...but this borrow...rustc
main.rs(60, 56): this return type evaluates to the'static
lifetime...
main.rs(61, 5): ...but this borrow...
如何告诉编译器只要引用有效我就只使用函数的结果(闭包)?
谢谢!
[编辑]
您是否需要一个包含引用和闭包的虚拟结构?
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 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
您需要在 return 类型上添加 + 'a
。然后编译器会告诉你你缺少 move
,但修复后,your code works:
fn get_cloned<'a>(obj: &'a MyStruct) -> impl Fn() -> MyStruct + 'a {
|| {obj.clone()}
}