泛型关联类型的生存期可能不够长



以以下示例(Playground(为例:

#![feature(generic_associated_types)]
#![allow(incomplete_features)]
trait Produce {
type CustomError<'a>;
fn produce<'a>(&'a self) -> Result<(), Self::CustomError<'a>>;
}
struct GenericProduce<T> {
val: T,
}
struct GenericError<'a, T> {
producer: &'a T,
}
impl<T> Produce for GenericProduce<T> {
type CustomError<'a> = GenericError<'a, T>;
fn produce<'a>(&'a self) -> Result<(), Self::CustomError<'a>> {
Err(GenericError{producer: &self.val})
}
}

GenericError具有生命周期,可以将其Produce作为参考。但是,此代码无法编译。它给了我错误:

error[E0309]: the parameter type `T` may not live long enough
--> src/lib.rs:19:5
|
18 | impl<T> Produce for GenericProduce<T> {
|      - help: consider adding an explicit lifetime bound...: `T: 'a`
19 |     type CustomError<'a> = GenericError<'a, T>;
|     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds

这个错误对我来说是有意义的,因为GenericError没有任何限制告诉它必须T'a。不过,我很难弄清楚如何解决问题。也许我的通用寿命放错了地方?

我希望捕捉到的特征是,任何Produce::CustomError都应该能够在返回时捕获self。也许我以错误的方式做这件事?

没有generic_associated_types的相同特征在特征本身中占据了一生。

trait Produce<'a> {
type CustomError;
fn produce(&'a self) -> Result<(), Self::CustomError>;
}
struct GenericProduce<T> {
val: T,
}
struct GenericError<'a, T> {
producer: &'a T,
}
impl<'a, T: 'a> Produce<'a> for GenericProduce<T> {
type CustomError = GenericError<'a, T>;
fn produce(&'a self) -> Result<(), Self::CustomError> {
Err(GenericError{producer: &self.val})
}
}

这告诉预先暗示,T它必须'a

最新更新