Rust 如何让impl Trait使用适当的生存期来引用一个具有另一个生存期的值?

Rust 如何让impl Trait使用适当的生存期来引用一个具有另一个生存期的值?,rust,lifetime,Rust,Lifetime,我有一个终生的结构: struct HasLifetime<'a>( /* ... */ ); 我想实现以下功能: fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> impl Foo { bar } 带有装箱特征对象的看似等价的函数编译: fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>)

我有一个终生的结构:

struct HasLifetime<'a>( /* ... */ );
我想实现以下功能:

fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> impl Foo {
    bar
}
带有装箱特征对象的看似等价的函数编译:

fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> Box<Foo + 'a> {
    Box::new(bar)
}
fn bar\u to\u foo{
框::新(条)
}
如何使用
impl Trait
定义
bar\u to\u 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
}
trait捕获(条:&'a mut haslifest+'a{
酒吧
}
谢天谢地,发生这种情况是因为引用是可变的。

这可能是一个bug。如果是,可能是相关的。
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
}