繁体   English   中英

我怎样才能让 impl Trait 使用适当的生命周期来对具有另一个生命周期的值进行可变引用?

[英]How can I get impl Trait to use the appropriate lifetime for a mutable reference to a value with another lifetime in it?

我有一个终生的结构:

struct HasLifetime<'a>( /* ... */ );

有一个特性Foo的实现:

impl<'a, 'b: 'a> Foo for &'a mut HasLifetime<'b> { }

我想实现以下功能:

fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> impl Foo {
    bar
}

这不会编译,因为返回的impl仅对'a有效。 但是,指定impl Foo + 'a导致:

error[E0909]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
 --> src/main.rs:7:60
  |
7 | fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut HasLifetime<'b>) -> impl Trait + 'a {
  |                                                            ^^^^^^^^^^^^^^^
  |
note: hidden type `&'a mut HasLifetime<'b>` captures the lifetime 'b as defined on the function body at 7:1
 --> src/main.rs:7:1
  |
7 | fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut HasLifetime<'b>) -> impl Trait + 'a {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

带有装箱 trait 对象的看似等效的函数编译:

fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> Box<Foo + 'a> {
    Box::new(bar)
}

如何使用impl Trait定义bar_to_foo

游乐场链接

您需要指出返回的值是建立在多个生命周期之上的。 但是,您不能对impl Trait使用多个生命周期边界,并且尝试这样做不会产生有用的错误消息

您可以使用一个技巧来创建一个具有生命周期参数的虚拟特征:

trait Captures<'a> {}
impl<'a, T: ?Sized> Captures<'a> for T {}

fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut HasLifetime<'b>) -> impl Trait + Captures<'b> + 'a {
    bar
}

值得庆幸的是,这仅在“隐藏”生命周期不变时才会发生,这是因为引用是可变的。

暂无
暂无

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

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