【问题标题】:Vector implementation problems向量实现问题
【发布时间】: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&lt;T&gt; 密集

我的 Vector&lt;T&gt; 结构包含 / 可以由 elements 类型的 [T] 定义。昨天,我正在阅读一些内存分配,并遇到了稀疏和密集的内存分配。我想知道 Rust 定义的数组是否密集(id est 所有项目都在(虚拟)内存中按顺序分配),因为这就是我想通过这些向量定义实现的目标。

【问题讨论】:

  • 如果你想对向量提供额外的操作,最简单的方法是通过组合:struct Vector&lt;T&gt; { inner: Vec&lt;T&gt; }。这样你仍然可以在Vector&lt;T&gt; 上定义自己的特征,但内部的Vec&lt;T&gt; 正在处理分配和其他低级问题。并且由于内联和零成本抽象,结果并不比仅使用向量慢,并且将编译成完全相同的代码。是的,Rust 的数组、切片和向量的元素在内存中都是连续的,即它们是密集的。

标签: arrays rust compiler-errors wrapper traits


【解决方案1】:

这些向量只能在给定大小后实例化 - 这意味着使用数组。

但是你还没有写数组;您已经编写了一个 slice,这意味着运行时选择大小,而不是一般选择大小。 [T] 具有动态大小;因此Vector&lt;T&gt; 具有动态大小;因此Vector&lt;T&gt; 不能在堆栈上传递或返回,必须始终在某个指针后面处理。这可能不是你想要的。

要声明一个数组,你必须写类型[T; N],而不是[T]。

#[derive(Debug)]
struct Vector<T, const N: usize> {
    elements: [T; N]
}

这样,Vector 将永远是Sized,避免了您询问的错误。您需要以相同的方式使现有的通用代码在N 和T 上通用。比如这里是Add的一个实现:

impl<T: num_traits::NumAssign, const N: usize> Add for Vector<T, N> {
    type Output = Self;
    fn add(mut self, other: Self) -> Self {
        for (self_el, other_el) in
            self.elements.iter_mut().zip(other.elements.into_iter())
        {
            *self_el += other_el;
        }
        self
    }
}

(它使用循环而不是 .collect(),因为 Iterator::collect() 不能收集到数组中,因为迭代器通常没有静态已知的长度。)

【讨论】:

  • 如果您需要动态长度,也可以选择使用盒装切片 (Box&lt;[T]&gt;),但由于某种原因不想要 Vec。然后你需要处理不同长度向量组合在一起的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多