【发布时间】:2020-06-11 02:36:45
【问题描述】:
举个例子(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功能目前不起作用。它只是启用语法,但它不使编译器能够对任何内容进行类型检查。实际实现该功能时,可能会出现这种情况。 -
我猜它正在进行中? github.com/rust-lang/rust/issues/44265
标签: rust traits generic-associated-types