Rust 认为参数是在 `impl Trait` 返回值中借用的,并抱怨“借用的值寿命不够长”

问题描述 投票:0回答:1

简化代码:

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)
    }
}
rust traits lifetime borrow-checker
1个回答
0
投票

函数签名

fn bar(a: &A) -> impl Foo

的缩写
fn bar<'a>(a: &'a A) -> impl Foo + 'a

所以你隐式地告诉编译器

bar
确实借用了
a

您可以通过简单地告诉它否则来修复它:

fn bar(a: &A) -> impl Foo + 'static
© www.soinside.com 2019 - 2024. All rights reserved.