|
| 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 | + |
| 16 | +#[deriving(Show,PartialEq,Eq)] |
| 17 | +struct Point { |
| 18 | + x: int, |
| 19 | + y: int |
| 20 | +} |
| 21 | + |
| 22 | +impl ops::Add<Point,Point> for Point { |
| 23 | + fn add(&self, other: &Point) -> Point { |
| 24 | + Point {x: self.x + (*other).x, y: self.y + (*other).y} |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl ops::Add<int,Point> for Point { |
| 29 | + fn add(&self, &other: &int) -> Point { |
| 30 | + Point {x: self.x + other, |
| 31 | + y: self.y + other} |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +pub fn main() { |
| 36 | + let mut p = Point {x: 10, y: 20}; |
| 37 | + p = p + Point {x: 101, y: 102}; |
| 38 | + assert_eq!(p, Point {x: 111, y: 122}); |
| 39 | + p = p + 1; |
| 40 | + assert_eq!(p, Point {x: 112, y: 123}); |
| 41 | +} |
0 commit comments