Niko Matsakis | 4af52ee | 2014-10-31 09:40:15 | [diff] [blame] | 1 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT |
| 2 | // file at the top-level directory of this distribution and at |
| 3 | // http://rust-lang.org/COPYRIGHT. |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | // option. This file may not be copied, modified, or distributed |
| 9 | // except according to those terms. |
| 10 | |
| 11 | // Test that we can overload the `+` operator for points so that two |
| 12 | // points can be added, and a point can be added to an integer. |
| 13 | |
| 14 | use std::ops; |
| 15 | |
Jorge Aparicio | 788181d | 2015-01-28 13:34:18 | [diff] [blame] | 16 | #[derive(Debug,PartialEq,Eq)] |
Niko Matsakis | 4af52ee | 2014-10-31 09:40:15 | [diff] [blame] | 17 | struct Point { |
Alex Crichton | 43bfaa4 | 2015-03-26 00:06:52 | [diff] [blame] | 18 | x: isize, |
| 19 | y: isize |
Niko Matsakis | 4af52ee | 2014-10-31 09:40:15 | [diff] [blame] | 20 | } |
| 21 | |
Jorge Aparicio | 99017f8 | 2014-12-31 20:45:13 | [diff] [blame] | 22 | impl ops::Add for Point { |
| 23 | type Output = Point; |
| 24 | |
Jorge Aparicio | 971add8 | 2014-12-01 22:33:22 | [diff] [blame] | 25 | fn add(self, other: Point) -> Point { |
| 26 | Point {x: self.x + other.x, y: self.y + other.y} |
Niko Matsakis | 4af52ee | 2014-10-31 09:40:15 | [diff] [blame] | 27 | } |
| 28 | } |
| 29 | |
Alex Crichton | 43bfaa4 | 2015-03-26 00:06:52 | [diff] [blame] | 30 | impl ops::Add<isize> for Point { |
Jorge Aparicio | 99017f8 | 2014-12-31 20:45:13 | [diff] [blame] | 31 | type Output = Point; |
| 32 | |
Alex Crichton | 43bfaa4 | 2015-03-26 00:06:52 | [diff] [blame] | 33 | fn add(self, other: isize) -> Point { |
Niko Matsakis | 4af52ee | 2014-10-31 09:40:15 | [diff] [blame] | 34 | Point {x: self.x + other, |
| 35 | y: self.y + other} |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | pub fn main() { |
| 40 | let mut p = Point {x: 10, y: 20}; |
| 41 | p = p + Point {x: 101, y: 102}; |
| 42 | assert_eq!(p, Point {x: 111, y: 122}); |
| 43 | p = p + 1; |
| 44 | assert_eq!(p, Point {x: 112, y: 123}); |
| 45 | } |