【发布时间】:2021-11-08 00:10:13
【问题描述】:
我正在尝试用 rust 编写一个数学向量库,但我遇到了一些我非常想解决的问题。我想解决两个问题:
- “
Sized未针对[T]实现”错误 - 使
element的Vecor<T>密集
最小的工作示例
#[derive(Debug)]
struct Vector<T> {
elements: [T]
}
// multiple base trait implementations
impl<T> /* … */ for Vector<T> { }
// one of multiple macros
macro_rules! impl_vector_normal_arithmetic {
($(impl $trait:ident for Vector { $function:ident($symbol:tt) })+) => {
$(
// ———————— Error: the trait `Sized` is not implemented for `[T]`
// vvvvvv
impl<T : Num> $trait for Vector<T> {
type Output = Self;
#[inline(always)]
fn $function(&self, other: Self) -> Self {
Self::new(
self.iter()
.zip(other.iter())
.map(|(&lhs, &rhs)| lhs $symbol rhs)
.collect()
)
}
}
)+
};
}
impl_vector_normal_arithmetic! {
impl Add for Vector { add(+) }
impl Sub for Vector { sub(-) }
impl Mul for Vector { mul(*) }
impl Div for Vector { div(/) }
}
“Sized 未针对 [T] 实现”错误
我的向量实现由一个通用向量定义组成,理论上,它应该能够包含无限大的向量。这些向量只能在给定大小后实例化 - 这意味着使用数组。然后使用宏来添加一些算术特征(Add、Sub、Div、Mul 等)。然而,这导致了一个问题。我无法实现这些函数,因为编译器告诉我 [T] 没有实现 Sized 特征。我明白错误告诉我什么,但我知道如何告诉编译器大小无关紧要(因为函数不在乎)。我可以做些什么来解决这个编译器错误?
使elements 的Vecor<T> 密集
我的 Vector<T> 结构包含 / 可以由 elements 类型的 [T] 定义。昨天,我正在阅读一些内存分配,并遇到了稀疏和密集的内存分配。我想知道 Rust 定义的数组是否密集(id est 所有项目都在(虚拟)内存中按顺序分配),因为这就是我想通过这些向量定义实现的目标。
【问题讨论】:
-
如果你想对向量提供额外的操作,最简单的方法是通过组合:
struct Vector<T> { inner: Vec<T> }。这样你仍然可以在Vector<T>上定义自己的特征,但内部的Vec<T>正在处理分配和其他低级问题。并且由于内联和零成本抽象,结果并不比仅使用向量慢,并且将编译成完全相同的代码。是的,Rust 的数组、切片和向量的元素在内存中都是连续的,即它们是密集的。
标签: arrays rust compiler-errors wrapper traits