MST

星途 面试题库

面试题:复杂场景下Rust二元运算符重载的性能优化与泛型应用

假设有一个矩阵(`Matrix`)结构体,它是一个二维数组,使用 `Vec<Vec<T>>` 表示,`T` 是泛型类型,可以是 `i32`、`f64` 等数值类型。实现矩阵加法的二元运算符 `+` 重载。在实现过程中,要考虑性能优化,例如避免不必要的内存分配和复制。同时,要确保代码在不同数值类型作为矩阵元素时都能正确工作,通过泛型和合适的特性(trait)约束来实现这一点。
22.5万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::ops::Add;

#[derive(Debug)]
struct Matrix<T> {
    data: Vec<Vec<T>>,
}

impl<T: Add<Output = T> + Clone> Add for Matrix<T> {
    type Output = Matrix<T>;

    fn add(self, other: Matrix<T>) -> Matrix<T> {
        assert_eq!(self.data.len(), other.data.len());
        assert!(self.data.iter().zip(other.data.iter()).all(|(a, b)| a.len() == b.len()));

        let mut result = Matrix {
            data: vec![vec![T::default(); self.data[0].len()]; self.data.len()],
        };

        for (i, row) in self.data.iter().enumerate() {
            for (j, element) in row.iter().enumerate() {
                result.data[i][j] = element.clone() + other.data[i][j].clone();
            }
        }

        result
    }
}