面试题答案
一键面试use std::ops::Add;
struct Vector<T> {
data: Vec<T>,
}
impl<T: Add<Output = T>> Add for Vector<T> {
type Output = Option<Vector<T>>;
fn add(self, other: Vector<T>) -> Self::Output {
if self.data.len() != other.data.len() {
return None;
}
let mut result_data = Vec::with_capacity(self.data.len());
for (a, b) in self.data.into_iter().zip(other.data.into_iter()) {
result_data.push(a + b);
}
Some(Vector { data: result_data })
}
}