问题描述
限时送ChatGPT账号..以下面的例子(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
作为引用.但是,此代码无法编译.它给了我错误:
The GenericError
has a lifetime to allow it to take Produce
as a reference. However, this code doesn't compile. It gives me the error:
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
.不过,我在弄清楚如何解决问题时遇到了麻烦.也许我的通用生命周期放错了地方?
This error makes sense to me because the GenericError
doesn't have any restriction telling it that T
must be 'a
. I'm having trouble figuring out how to solve the problem though. Perhaps my generic lifetimes are misplaced?
我希望捕获的特征的特征是任何 Produce::CustomError
都应该能够在返回中捕获 self
.也许我以错误的方式处理这个问题?
The feature of the trait I wish to capture is that any Produce::CustomError
should be able to capture self
in a return. Perhaps I am going about this in the wrong way?
推荐答案
没有 generic_related_types
的相同 trait 在 trait 本身中占用生命周期.
The same trait without generic_associated_types
takes the lifetime in the trait itself.
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
.
This tells the impl upfront that T
that it must be 'a
.
这篇关于泛型关联类型可能存在的时间不够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论