[英]How can I get impl Trait to use the appropriate lifetime for a mutable reference to a value with another lifetime in it?
I have a struct with a lifetime:我有一个终生的结构:
struct HasLifetime<'a>( /* ... */ );
There is there is an implementation of the trait Foo
:有一个特性
Foo
的实现:
impl<'a, 'b: 'a> Foo for &'a mut HasLifetime<'b> { }
I want to implement the following function:我想实现以下功能:
fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> impl Foo {
bar
}
This won't compile because the returned impl
is only valid for 'a
.这不会编译,因为返回的
impl
仅对'a
有效。 However, specifying impl Foo + 'a
results in:但是,指定
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 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The seemingly equivalent function with a boxed trait object compiles:带有装箱 trait 对象的看似等效的函数编译:
fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> Box<Foo + 'a> {
Box::new(bar)
}
How can I define bar_to_foo
with impl Trait
?如何使用
impl Trait
定义bar_to_foo
?
You need to indicate that the returned value is built upon multiple lifetimes.您需要指出返回的值是建立在多个生命周期之上的。 However, you can't use multiple lifetime bounds with
impl Trait
, and attempting to do so doesn't have a useful error message .但是,您不能对
impl Trait
使用多个生命周期边界,并且尝试这样做不会产生有用的错误消息。
There's a trick you can use that involves creating a dummy trait that has a lifetime parameter: 您可以使用一个技巧来创建一个具有生命周期参数的虚拟特征:
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
}
Thankfully, this only occurs when the "hidden" lifetime is invariant , which occurs because the reference is mutable.值得庆幸的是,这仅在“隐藏”生命周期不变时才会发生,这是因为引用是可变的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.