Advertisement
cwchen

[Rust] Implement Add trait for Vector class.

Sep 14th, 2017
971
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.49 KB | None | 0 0
  1. // Overloaded binary '+' operator
  2. impl<T> Add for Vector<T> where T: Copy + fmt::Display + num::Num {
  3.     type Output = Vector<T>;
  4.  
  5.     fn add(self: Vector<T>, other: Vector<T>) -> Vector<T> {
  6.         if self.vec.len() != other.vec.len() {
  7.             panic!("The length of the two vectors are unequal");
  8.         }
  9.  
  10.         let mut v: Vec<T> = Vec::new();
  11.  
  12.         for i in 0..(self.vec.len()) {
  13.             v.push(self.vec[i] + other.vec[i]);
  14.         }
  15.  
  16.         Vector{ vec: v }
  17.     }
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement