将集合移出上下文

Moving collection out of context

我正在尝试使用生命周期实现一些特征,但像往常一样,我正在与借用检查器作斗争。

我的性格是这样的:

pub struct Matrix<T> {
    pub cols: usize,
    pub rows: usize,
    pub data: Vec<T>
}

impl<'a, 'b, T: Copy + Mul<T, Output=T>> Mul<&'b T> for &'a Matrix<T> {
    type Output = Matrix<T>;

    fn mul(self, f: &T) -> Matrix<T> {
        let new_data : Vec<T> = self.data.into_iter().map(|v| v * (*f)).collect();

        Matrix {
            cols: self.cols,
            rows: self.rows,
            data: new_data
        }
    }
}

游乐场link

这会产生以下错误:

error: cannot move out of borrowed content

我想我明白为什么会这样:我在借用自己,所以我无法复制数据。我该如何解决这个问题?

发生这种情况是因为您在矢量上使用 into_iter()。因为你在 T 上绑定了 Copy,这是不必要的;您可以只使用 iter() 并取消引用闭包中的参数:

pub struct Matrix<T> {
    pub cols: usize,
    pub rows: usize,
    pub data: Vec<T>
}

impl<'a, 'b, T: Copy + Mul<T, Output=T>> Mul<&'b T> for &'a Matrix<T> {
    type Output = Matrix<T>;

    fn mul(self, f: &T) -> Matrix<T> {
        let new_data: Vec<T> = self.data.iter().map(|v| *v * *f).collect();

        Matrix {
            cols: self.cols,
            rows: self.rows,
            data: new_data
        }
    }
}

(playground)