我有这种类型:
struct Wrap<T>(Vec<T>);
我想实现std::ops::Index
并返回对特征对象的引用。这是我的第一次尝试(游乐场):
use std::ops::Index;
use std::fmt::Display;
impl<T> Index<usize> for Wrap<T>
where
T: Display
{
type Output = Display;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
这不起作用并导致此错误:
error[E0310]: the parameter type `T` may not live long enough
--> src/main.rs:13:9
|
7 | impl<T> Index<usize> for Wrap<T>
| - help: consider adding an explicit lifetime bound `T: 'static`...
...
13 | &self.0[index]
| ^^^^^^^^^^^^^^
|
note: ...so that the type `T` will meet its required lifetime bounds
--> src/main.rs:13:9
|
13 | &self.0[index]
| ^^^^^^^^^^^^^^
我想我知道为什么会发生这种情况:type Output = Display
相当于type Output = Display + 'static
每个 trait 对象都有一个默认为'static
.
所以现在我可以将'static
绑定添加到我的参数T
,但我认为这是过度约束。当不使用关联类型时,我可以轻松实现这样的方法:
impl<T> Wrap<T>
where
T: Display,
{
fn my_index(&self, index: usize) -> &Display {
&self.0[index]
}
}
不需要'static
限制,因为现在签名去糖:
fn my_index<'a>(&'a self, index: usize) -> &'a Display + 'a
这是有道理的:特征对象必须至少存在'a
. (带有所有代码的游乐场)。
但是我可以使用关联类型(如Index
特征)来完成这项工作吗?我觉得这可能适用于泛型关联类型,但是(a)我不确定并且(b)它们还没有实现。