MST

星途 面试题库

面试题:Rust泛型结构体的高级特性及优化

假设有一个复杂的Rust泛型结构体`Matrix`,代表一个矩阵,其元素类型是泛型的。矩阵支持常见的操作如转置、矩阵乘法等。要求:1. 泛型类型参数需要满足必要的trait限定,以支持矩阵操作。2. 利用Rust的所有权和生命周期特性优化矩阵操作的性能,避免不必要的内存拷贝。请写出完整的结构体定义、方法实现及简要的性能优化说明。
29.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 定义矩阵操作所需的trait
trait MatrixElement: Copy + Clone + std::ops::Mul<Output = Self> + std::ops::Add<Output = Self> {
    fn zero() -> Self;
}

// 定义Matrix结构体
struct Matrix<T>
where
    T: MatrixElement,
{
    data: Vec<T>,
    rows: usize,
    cols: usize,
}

impl<T> Matrix<T>
where
    T: MatrixElement,
{
    // 构造函数
    fn new(rows: usize, cols: usize) -> Self {
        Matrix {
            data: vec![T::zero(); rows * cols],
            rows,
            cols,
        }
    }

    // 获取矩阵元素
    fn get(&self, row: usize, col: usize) -> Option<&T> {
        if row < self.rows && col < self.cols {
            Some(&self.data[row * self.cols + col])
        } else {
            None
        }
    }

    // 设置矩阵元素
    fn set(&mut self, row: usize, col: usize, value: T) -> Option<()> {
        if row < self.rows && col < self.cols {
            self.data[row * self.cols + col] = value;
            Some(())
        } else {
            None
        }
    }

    // 转置矩阵
    fn transpose(self) -> Matrix<T> {
        let mut result = Matrix::new(self.cols, self.rows);
        for i in 0..self.rows {
            for j in 0..self.cols {
                result.set(j, i, *self.get(i, j).unwrap()).unwrap();
            }
        }
        result
    }

    // 矩阵乘法
    fn multiply(&self, other: &Matrix<T>) -> Option<Matrix<T>> {
        if self.cols != other.rows {
            return None;
        }
        let mut result = Matrix::new(self.rows, other.cols);
        for i in 0..self.rows {
            for j in 0..other.cols {
                let mut sum = T::zero();
                for k in 0..self.cols {
                    sum = sum + self.get(i, k).unwrap() * other.get(k, j).unwrap();
                }
                result.set(i, j, sum).unwrap();
            }
        }
        Some(result)
    }
}

性能优化说明:

  1. 所有权:在transpose方法中,采用了self参数,意味着原矩阵的所有权被转移,避免了重复的内存分配和拷贝。
  2. 生命周期:在multiply方法中,使用&self&other引用,明确了矩阵在方法调用期间的生命周期,确保不会发生悬空引用。并且操作过程中直接操作矩阵内部的数据,避免了不必要的数据拷贝。
  3. 泛型trait限定:通过限定泛型类型参数T必须实现CopyCloneMulAdd trait,并提供zero方法,保证了矩阵操作的基本运算需求,同时Copy trait 有助于减少数据拷贝。