您需要添加
+ use<>
上
make_struct()
实现以防止它捕获其生命周期
str
论点:
impl ResultTrait for ResultStruct {
fn make_struct(&self, str: &String) -> impl TestTrait + use<> {
TestStruct {}
}
// ...
}
Playground
use<>
这两个参数的生命周期都记录在
impl TestTrait
返回,因为这是默认值,因为编译器只使用签名来推断生存期,而不是函数体。这个默认值是合理的,因为它允许返回的值使用传递给函数的引用,这是经常需要的。没有
use
// anonymous struct returned by `make_struct()`
struct Anon<'a, 'b> {
inner: TestStruct,
_phantom: PhantomData<(&'a ResultStruct, &'b String)>,
}
impl TestTrait for Anon<'_, '_> {
// if TestTrait had methods, they'd forward to self.inner
}
impl ResultTrait for ResultStruct {
fn make_struct<'a, 'b>(&'a self, str: &'b String) -> Anon<'a, 'b> {
// returns an anonymous struct tied to the lifetimes of self and str
Anon {
inner: TestStruct {},
_phantom: PhantomData,
}
}
// ...
}
Playground
该实现导致了相同的借用检查错误,这是由以下原因引起的
Anon
从返回
test_lifetime()
同时捕获局部变量的生存期
怎么翻译
.
使用<>
导致脱糖,其中
匿名
no longer captures
'b
寿命(
&self
仍然被捕获,据我所知,这不能被排除在外)。有了这样的去糖,编译就成功了,就像它对
使用<>
.
使用
this article
.