打算写一个科学计算库,从向量运算入手。费了一天功夫,终于完成了这十来行代码。这里面牵涉到变量引用、解引用,也不知道用法是否正确。感觉 rust 从各方面颠覆我的想象。
use std::ops::{Add, Sub, Mul, Div};pub struct RowVec<T>(Vec<T>);
impl <T: Add<Output = T> + Copy + Clone> Add for RowVec<T> {type Output = Self;fn add(self, other: Self) -> Self {let x = self.0.iter();let y = other.0.iter();let z = x.zip(y).map(|(a,b)| *a + *b).collect::<Vec<T>>();Self(z)}
}
#[test]
fn test_add() {let x = RowVec(vec![1,2,3]);let y = RowVec(vec![4,5,6]);let z = x + y;for p in z.0.iter() {println!("{:?}", p);}
}