【发布时间】:2020-07-22 12:29:30
【问题描述】:
我正在尝试为具有泛型类型的结构实现具有泛型关联类型的特征。我正在使用夜间版本1.47.0-nightly (2020-07-20 f9a3086363f214f2b56b)。
我有结构 S1 和 S2,一个带有 GAT 的 trait 和一个实现:
#![allow(incomplete_features)]
#![feature(generic_associated_types)]
use core::marker::PhantomData;
struct S1<T>(PhantomData<T>);
struct S2<'a, T: 'a>(PhantomData<(T, &'a ())>);
trait MyTrait {
type A<'a>;
}
impl MyTrait for S1<f64> {
type A<'a> = S2<'a, f64>;
}
这可行,但我想为通用 T 实现特征:
impl<T> MyTrait for S1<T> {
type A<'a> = S2<'a, T>;
}
我现在需要指出T 的寿命与'a 一样长,这是S2 的定义所要求的:
error[E0309]: the parameter type `T` may not live long enough
--> src/lib.rs:14:5
|
13 | impl<T> MyTrait for S1<T> {
| - help: consider adding an explicit lifetime bound...: `T: 'a`
14 | type A<'a> = S2<'a, T>;
| ^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds
如何做到这一点?
我找到了Generic associated type may not live long enough,但它可能已经过时,因为它声称代码尚未实现。但是,为什么像this 这样的复杂代码会编译(并按预期工作)?
【问题讨论】:
-
添加
T: 'static绑定的潜在缺点是什么? -
如果
T的寿命与'a一样长,尽可能'a,然后T: 'static。
标签: generics rust traits lifetime generic-associated-types