问题描述
我有一个有生命的结构:
I have a struct with a lifetime:
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
会导致:
This won't compile because the returned impl
is only valid for 'a
. However, specifying impl Foo + 'a
results in:
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:
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
使用多个生存期限制,而尝试使用没有有用的错误消息.
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.
有您可以使用的技巧,其中包括创建一个具有生存期参数的虚拟特征:
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.
这篇关于如何获得impl Trait使用适当的生存期来对其中包含另一个生存期的值进行可变引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!