通用关联类型可能寿命不够长
Generic associated type may not live long enough
举个例子(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
都应该能够捕获 return 中的 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})
}
}
这预先告诉 impl T
它必须是 'a
.
举个例子(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
都应该能够捕获 return 中的 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})
}
}
这预先告诉 impl T
它必须是 'a
.