相关疑难解决方法(0)

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

我有一个终生的结构:

struct HasLifetime<'a>( /* ... */ );
Run Code Online (Sandbox Code Playgroud)

有一个 trait 的实现Foo

impl<'a, 'b: 'a> Foo for &'a mut HasLifetime<'b> { }
Run Code Online (Sandbox Code Playgroud)

我想实现以下功能:

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

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

struct HasLifetime<'a>( /* ... */ );
Run Code Online (Sandbox Code Playgroud)

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

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

我如何定义bar_to_fooimpl Trait

游乐场链接

lifetime rust

9
推荐指数
1
解决办法
2493
查看次数

标签 统计

lifetime ×1

rust ×1