简化代码:
struct A(/**/);
trait Foo {}
trait Bar {
fn bar(a: &A) -> impl Foo;
fn baz() -> impl Foo {
let a = A();
Self::bar(&a)
}
}
错误:
error[E0597]: `a` does not live long enough
--> src/lib.rs:10:19
|
9 | let a = A();
| - binding `a` declared here
10 | Self::bar(&a)
| ----------^^-
| | |
| | borrowed value does not live long enough
| argument requires that `a` is borrowed for `'static`
11 | }
| - `a` dropped here while still borrowed
可以通过返回实现
Foo
或 Box<dyn Foo>
而不是 impl Foo
的具体类型来解决这个问题,但我想继续返回 impl Foo
而不引入额外的开销。
有效但我不想要的示例:
struct A(/**/);
trait Foo {}
struct B;
impl Foo for B {}
trait Bar {
fn bar(a: &A) -> B;
fn baz() -> impl Foo {
let a = A();
Self::bar(&a)
}
}
struct A(/**/);
trait Foo {}
trait Bar {
fn bar(a: &A) -> Box<dyn Foo>;
fn baz() -> Box<dyn Foo> {
let a = A();
Self::bar(&a)
}
}
函数签名
fn bar(a: &A) -> impl Foo
是
的缩写fn bar<'a>(a: &'a A) -> impl Foo + 'a
所以你隐式地告诉编译器
bar
确实借用了a
。
您可以通过简单地告诉它否则来修复它:
fn bar(a: &A) -> impl Foo + 'static