簡體   English   中英

Rust:向量實現問題

[英]Rust: vector implementation problems

我正在嘗試用 rust 編寫一個數學向量庫,但是我遇到了一些我很想解決的問題。 我想解決兩個問題:

  • [T]未實現Sized ”錯誤
  • 使Vecor<T>element密集

最小工作示例

#[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(/) }
}

[T]未實現Sized ”錯誤

我對向量的實現由一個通用向量定義組成,理論上,該定義應該能夠包含無限大的向量。 這些向量只能在給定大小后實例化 - 這意味着使用數組。 然后使用宏來添加一些算術特征(Add、Sub、Div、Mul 等)。 然而,這會導致一個問題。 我無法實現這些函數,因為編譯器告訴我[T]沒有實現Sized特征。 我確實理解錯誤告訴我什么,但我知道如何告訴編譯器大小無關緊要(因為函數不在乎)。 我該怎么做才能解決這個編譯器錯誤?

使Vecor<T>elements密集

我的Vector<T>結構包含 / 可以由[T]類型的elements定義。 昨天,我正在閱讀一些內存分配,並遇到了稀疏和密集的內存分配。 我想知道由 Rust 定義的數組是否是密集的(id est 所有項目在(虛擬)內存中按順序分配),因為這就是我想要通過這些向量定義實現的目標。

這些向量只能在給定大小后實例化 - 這意味着使用數組。

但是你還沒有寫數組; 您已經編寫了一個slice ,這意味着運行時選擇的大小,而不是一般的大小選擇。 [T]具有動態大小; 因此Vector<T>具有動態大小; 因此Vector<T>不能在堆棧上傳遞或返回,並且必須始終在某個指針之后進行處理。 這可能不是您想要的。

要聲明一個數組,您必須編寫類型[T; N] [T; N] ,而不是[T]

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

這樣, Vector將始終為Sized ,避免您詢問的錯誤。 您需要以相同的方式使現有的通用代碼在NT通用。 例如,這是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()不能收集到數組中,因為迭代器通常沒有靜態已知的長度。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM