我有一个终生的结构:
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_foo与impl Trait?