From 87b064b249657c8e65079d01beb77409f69d49cd Mon Sep 17 00:00:00 2001 From: Marijn Haverbeke Date: Thu, 26 Jan 2012 12:26:14 +0100 Subject: First stab at operator overloading When no built-in interpretation is found for one of the operators mentioned below, the typechecker will try to turn it into a method call with the name written next to it. For binary operators, the method will be called on the LHS with the RHS as only parameter. Binary: + op_add - op_sub * op_mul / op_div % op_rem & op_and | op_or ^ op_xor << op_shift_left >> op_shift_right >>> op_ashift_right Unary: - op_neg ! op_not Overloading of the indexing ([]) operator isn't finished yet. Issue #1520 --- src/test/compile-fail/minus-string.rs | 2 +- src/test/run-pass/operator-overloading.rs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 src/test/run-pass/operator-overloading.rs (limited to 'src/test') diff --git a/src/test/compile-fail/minus-string.rs b/src/test/compile-fail/minus-string.rs index f77756942b1..776d82bf492 100644 --- a/src/test/compile-fail/minus-string.rs +++ b/src/test/compile-fail/minus-string.rs @@ -1,3 +1,3 @@ -// error-pattern:applying unary minus to non-numeric type `str` +// error-pattern:can not apply unary operator `-` to type `str` fn main() { -"foo"; } diff --git a/src/test/run-pass/operator-overloading.rs b/src/test/run-pass/operator-overloading.rs new file mode 100644 index 00000000000..4265f0023b7 --- /dev/null +++ b/src/test/run-pass/operator-overloading.rs @@ -0,0 +1,17 @@ +type point = {x: int, y: int}; + +impl add_point for point { + fn op_add(other: point) -> point { + {x: self.x + other.x, y: self.y + other.y} + } + fn op_neg() -> point { + {x: -self.x, y: -self.y} + } +} + +fn main() { + let p = {x: 10, y: 20}; + p += {x: 1, y: 2}; + assert p + {x: 5, y: 5} == {x: 16, y: 27}; + assert -p == {x: -11, y: -22}; +} -- cgit 1.4.1-3-g733a5