通用结构中索引容器的向量
Vector of indexed containers in generic struct
我正在尝试使用索引容器的矢量,e.i。实现 std::ops::Index
的任何类型,但我找不到在实现部分为 type Output
分配类型的解决方案。
据我所知应该是这样的:
pub struct Holder<C: Index<usize> + ExactSizeIterator> {
containers: Vec<C>
}
impl<C: Index<usize>, T> Index<usize> for Holder<C> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
todo!();
}
}
但这显然以
结束
the type parameter T
is not constrained by the impl trait, self type, or predicates
unconstrained type parameter rustc(E0207)
(为澄清起见,错误指向 impl<C: Index<usize>, T>
中的 T
)
但是我不知道有什么方法可以将另一个泛型类型添加到 Holder
的定义中,这不仅仅是一个未使用的字段。
Holder
的目的是包含其他可索引的容器,Holder
的索引函数应该 return 来自其中一个容器的项目。
如果 post 中有任何遗漏,请告诉我。任何帮助或指点将不胜感激,谢谢!
您可以像这样引用泛型参数定义的关联类型:
type Output = C::Output;
您可能想完全删除 T
并直接从 C
推导出 Output
类型:
impl<C: Index<usize> + ExactSizeIterator> Index<usize> for Holder<C> {
type Output = C::Output; // <--------
fn index(&self, index: usize) -> &Self::Output {
todo!();
}
}
我正在尝试使用索引容器的矢量,e.i。实现 std::ops::Index
的任何类型,但我找不到在实现部分为 type Output
分配类型的解决方案。
据我所知应该是这样的:
pub struct Holder<C: Index<usize> + ExactSizeIterator> {
containers: Vec<C>
}
impl<C: Index<usize>, T> Index<usize> for Holder<C> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
todo!();
}
}
但这显然以
结束the type parameter
T
is not constrained by the impl trait, self type, or predicates unconstrained type parameter rustc(E0207)
(为澄清起见,错误指向 impl<C: Index<usize>, T>
中的 T
)
但是我不知道有什么方法可以将另一个泛型类型添加到 Holder
的定义中,这不仅仅是一个未使用的字段。
Holder
的目的是包含其他可索引的容器,Holder
的索引函数应该 return 来自其中一个容器的项目。
如果 post 中有任何遗漏,请告诉我。任何帮助或指点将不胜感激,谢谢!
您可以像这样引用泛型参数定义的关联类型:
type Output = C::Output;
您可能想完全删除 T
并直接从 C
推导出 Output
类型:
impl<C: Index<usize> + ExactSizeIterator> Index<usize> for Holder<C> {
type Output = C::Output; // <--------
fn index(&self, index: usize) -> &Self::Output {
todo!();
}
}