1 // Copyright 2012 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.
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.
11 //! Overloadable operators
13 //! Implementing these traits allows you to get an effect similar to
14 //! overloading operators.
16 //! The values for the right hand side of an operator are automatically
17 //! borrowed, so `a + b` is sugar for `a.add(&b)`.
19 //! All of these traits are imported by the prelude, so they are available in
20 //! every Rust program.
24 //! This example creates a `Point` struct that implements `Add` and `Sub`, and then
25 //! demonstrates adding and subtracting two `Point`s.
28 //! #![feature(associated_types)]
30 //! use std::ops::{Add, Sub};
38 //! impl Add for Point {
39 //! type Output = Point;
41 //! fn add(self, other: Point) -> Point {
42 //! Point {x: self.x + other.x, y: self.y + other.y}
46 //! impl Sub for Point {
47 //! type Output = Point;
49 //! fn sub(self, other: Point) -> Point {
50 //! Point {x: self.x - other.x, y: self.y - other.y}
54 //! println!("{}", Point {x: 1, y: 0} + Point {x: 2, y: 3});
55 //! println!("{}", Point {x: 1, y: 0} - Point {x: 2, y: 3});
59 //! See the documentation for each trait for a minimum implementation that prints
60 //! something to the screen.
63 use iter::{Step, Iterator,DoubleEndedIterator,ExactSizeIterator};
65 use option::Option::{mod, Some, None};
67 /// The `Drop` trait is used to run some code when a value goes out of scope. This
68 /// is sometimes called a 'destructor'.
72 /// A trivial implementation of `Drop`. The `drop` method is called when `_x` goes
73 /// out of scope, and therefore `main` prints `Dropping!`.
78 /// impl Drop for HasDrop {
79 /// fn drop(&mut self) {
80 /// println!("Dropping!");
90 /// The `drop` method, called when the value goes out of scope.
94 /// The `Add` trait is used to specify the functionality of `+`.
98 /// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up
99 /// calling `add`, and therefore, `main` prints `Adding!`.
102 /// #![feature(associated_types)]
104 /// use std::ops::Add;
106 /// #[deriving(Copy)]
109 /// impl Add for Foo {
110 /// type Output = Foo;
112 /// fn add(self, _rhs: Foo) -> Foo {
113 /// println!("Adding!");
123 pub trait Add<RHS=Self> {
126 /// The method for the `+` operator
127 fn add(self, rhs: RHS) -> Self::Output;
130 macro_rules! add_impl {
136 fn add(self, other: $t) -> $t { self + other }
141 add_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
143 /// The `Sub` trait is used to specify the functionality of `-`.
147 /// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up
148 /// calling `sub`, and therefore, `main` prints `Subtracting!`.
151 /// #![feature(associated_types)]
153 /// use std::ops::Sub;
155 /// #[deriving(Copy)]
158 /// impl Sub for Foo {
159 /// type Output = Foo;
161 /// fn sub(self, _rhs: Foo) -> Foo {
162 /// println!("Subtracting!");
172 pub trait Sub<RHS=Self> {
175 /// The method for the `-` operator
176 fn sub(self, rhs: RHS) -> Self::Output;
179 macro_rules! sub_impl {
185 fn sub(self, other: $t) -> $t { self - other }
190 sub_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
192 /// The `Mul` trait is used to specify the functionality of `*`.
196 /// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up
197 /// calling `mul`, and therefore, `main` prints `Multiplying!`.
200 /// #![feature(associated_types)]
202 /// use std::ops::Mul;
204 /// #[deriving(Copy)]
207 /// impl Mul for Foo {
208 /// type Output = Foo;
210 /// fn mul(self, _rhs: Foo) -> Foo {
211 /// println!("Multiplying!");
221 pub trait Mul<RHS=Self> {
224 /// The method for the `*` operator
225 fn mul(self, rhs: RHS) -> Self::Output;
228 macro_rules! mul_impl {
234 fn mul(self, other: $t) -> $t { self * other }
239 mul_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
241 /// The `Div` trait is used to specify the functionality of `/`.
245 /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up
246 /// calling `div`, and therefore, `main` prints `Dividing!`.
249 /// #![feature(associated_types)]
251 /// use std::ops::Div;
253 /// #[deriving(Copy)]
256 /// impl Div for Foo {
257 /// type Output = Foo;
259 /// fn div(self, _rhs: Foo) -> Foo {
260 /// println!("Dividing!");
270 pub trait Div<RHS=Self> {
273 /// The method for the `/` operator
274 fn div(self, rhs: RHS) -> Self::Output;
277 macro_rules! div_impl {
283 fn div(self, other: $t) -> $t { self / other }
288 div_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
290 /// The `Rem` trait is used to specify the functionality of `%`.
294 /// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up
295 /// calling `rem`, and therefore, `main` prints `Remainder-ing!`.
298 /// #![feature(associated_types)]
300 /// use std::ops::Rem;
302 /// #[deriving(Copy)]
305 /// impl Rem for Foo {
306 /// type Output = Foo;
308 /// fn rem(self, _rhs: Foo) -> Foo {
309 /// println!("Remainder-ing!");
319 pub trait Rem<RHS=Self> {
322 /// The method for the `%` operator
323 fn rem(self, rhs: RHS) -> Self::Output;
326 macro_rules! rem_impl {
332 fn rem(self, other: $t) -> $t { self % other }
337 macro_rules! rem_float_impl {
338 ($t:ty, $fmod:ident) => {
343 fn rem(self, other: $t) -> $t {
344 extern { fn $fmod(a: $t, b: $t) -> $t; }
345 unsafe { $fmod(self, other) }
351 rem_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 }
352 rem_float_impl! { f32, fmodf }
353 rem_float_impl! { f64, fmod }
355 /// The `Neg` trait is used to specify the functionality of unary `-`.
359 /// A trivial implementation of `Neg`. When `-Foo` happens, it ends up calling
360 /// `neg`, and therefore, `main` prints `Negating!`.
363 /// #![feature(associated_types)]
365 /// use std::ops::Neg;
369 /// impl Copy for Foo {}
371 /// impl Neg for Foo {
372 /// type Output = Foo;
374 /// fn neg(self) -> Foo {
375 /// println!("Negating!");
388 /// The method for the unary `-` operator
389 fn neg(self) -> Self::Output;
392 macro_rules! neg_impl {
398 fn neg(self) -> $t { -self }
403 macro_rules! neg_uint_impl {
404 ($t:ty, $t_signed:ty) => {
409 fn neg(self) -> $t { -(self as $t_signed) as $t }
414 neg_impl! { int i8 i16 i32 i64 f32 f64 }
416 neg_uint_impl! { uint, int }
417 neg_uint_impl! { u8, i8 }
418 neg_uint_impl! { u16, i16 }
419 neg_uint_impl! { u32, i32 }
420 neg_uint_impl! { u64, i64 }
423 /// The `Not` trait is used to specify the functionality of unary `!`.
427 /// A trivial implementation of `Not`. When `!Foo` happens, it ends up calling
428 /// `not`, and therefore, `main` prints `Not-ing!`.
431 /// #![feature(associated_types)]
433 /// use std::ops::Not;
437 /// impl Copy for Foo {}
439 /// impl Not for Foo {
440 /// type Output = Foo;
442 /// fn not(self) -> Foo {
443 /// println!("Not-ing!");
456 /// The method for the unary `!` operator
457 fn not(self) -> Self::Output;
460 macro_rules! not_impl {
466 fn not(self) -> $t { !self }
471 not_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 }
473 /// The `BitAnd` trait is used to specify the functionality of `&`.
477 /// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up
478 /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`.
481 /// #![feature(associated_types)]
483 /// use std::ops::BitAnd;
485 /// #[deriving(Copy)]
488 /// impl BitAnd for Foo {
489 /// type Output = Foo;
491 /// fn bitand(self, _rhs: Foo) -> Foo {
492 /// println!("Bitwise And-ing!");
502 pub trait BitAnd<RHS=Self> {
505 /// The method for the `&` operator
506 fn bitand(self, rhs: RHS) -> Self::Output;
509 macro_rules! bitand_impl {
515 fn bitand(self, rhs: $t) -> $t { self & rhs }
520 bitand_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 }
522 /// The `BitOr` trait is used to specify the functionality of `|`.
526 /// A trivial implementation of `BitOr`. When `Foo | Foo` happens, it ends up
527 /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`.
530 /// #![feature(associated_types)]
532 /// use std::ops::BitOr;
534 /// #[deriving(Copy)]
537 /// impl BitOr for Foo {
538 /// type Output = Foo;
540 /// fn bitor(self, _rhs: Foo) -> Foo {
541 /// println!("Bitwise Or-ing!");
551 pub trait BitOr<RHS=Self> {
554 /// The method for the `|` operator
555 fn bitor(self, rhs: RHS) -> Self::Output;
558 macro_rules! bitor_impl {
564 fn bitor(self, rhs: $t) -> $t { self | rhs }
569 bitor_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 }
571 /// The `BitXor` trait is used to specify the functionality of `^`.
575 /// A trivial implementation of `BitXor`. When `Foo ^ Foo` happens, it ends up
576 /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`.
579 /// #![feature(associated_types)]
581 /// use std::ops::BitXor;
583 /// #[deriving(Copy)]
586 /// impl BitXor for Foo {
587 /// type Output = Foo;
589 /// fn bitxor(self, _rhs: Foo) -> Foo {
590 /// println!("Bitwise Xor-ing!");
600 pub trait BitXor<RHS=Self> {
603 /// The method for the `^` operator
604 fn bitxor(self, rhs: RHS) -> Self::Output;
607 macro_rules! bitxor_impl {
613 fn bitxor(self, other: $t) -> $t { self ^ other }
618 bitxor_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 }
620 /// The `Shl` trait is used to specify the functionality of `<<`.
624 /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up
625 /// calling `shl`, and therefore, `main` prints `Shifting left!`.
628 /// #![feature(associated_types)]
630 /// use std::ops::Shl;
632 /// #[deriving(Copy)]
635 /// impl Shl<Foo> for Foo {
636 /// type Output = Foo;
638 /// fn shl(self, _rhs: Foo) -> Foo {
639 /// println!("Shifting left!");
652 /// The method for the `<<` operator
653 fn shl(self, rhs: RHS) -> Self::Output;
656 macro_rules! shl_impl {
658 impl Shl<uint> for $t {
662 fn shl(self, other: uint) -> $t {
669 shl_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 }
671 /// The `Shr` trait is used to specify the functionality of `>>`.
675 /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up
676 /// calling `shr`, and therefore, `main` prints `Shifting right!`.
679 /// #![feature(associated_types)]
681 /// use std::ops::Shr;
683 /// #[deriving(Copy)]
686 /// impl Shr<Foo> for Foo {
687 /// type Output = Foo;
689 /// fn shr(self, _rhs: Foo) -> Foo {
690 /// println!("Shifting right!");
703 /// The method for the `>>` operator
704 fn shr(self, rhs: RHS) -> Self::Output;
707 macro_rules! shr_impl {
709 impl Shr<uint> for $t {
713 fn shr(self, other: uint) -> $t { self >> other }
718 shr_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 }
720 // NOTE(stage0) remove trait after a snapshot
722 #[allow(missing_docs)]
724 pub trait Index<Sized? Index, Sized? Result> for Sized? {
725 /// The method for the indexing (`Foo[Bar]`) operation
726 fn index<'a>(&'a self, index: &Index) -> &'a Result;
729 /// The `Index` trait is used to specify the functionality of indexing operations
730 /// like `arr[idx]` when used in an immutable context.
734 /// A trivial implementation of `Index`. When `Foo[Foo]` happens, it ends up
735 /// calling `index`, and therefore, `main` prints `Indexing!`.
738 /// #![feature(associated_types)]
740 /// use std::ops::Index;
742 /// #[deriving(Copy)]
745 /// impl Index<Foo> for Foo {
746 /// type Output = Foo;
748 /// fn index<'a>(&'a self, _index: &Foo) -> &'a Foo {
749 /// println!("Indexing!");
758 #[cfg(not(stage0))] // NOTE(stage0) remove cfg after a snapshot
760 pub trait Index<Sized? Index> for Sized? {
763 /// The method for the indexing (`Foo[Bar]`) operation
764 fn index<'a>(&'a self, index: &Index) -> &'a Self::Output;
767 // NOTE(stage0) remove trait after a snapshot
769 #[allow(missing_docs)]
771 pub trait IndexMut<Sized? Index, Sized? Result> for Sized? {
772 /// The method for the indexing (`Foo[Bar]`) operation
773 fn index_mut<'a>(&'a mut self, index: &Index) -> &'a mut Result;
776 /// The `IndexMut` trait is used to specify the functionality of indexing
777 /// operations like `arr[idx]`, when used in a mutable context.
781 /// A trivial implementation of `IndexMut`. When `Foo[Foo]` happens, it ends up
782 /// calling `index_mut`, and therefore, `main` prints `Indexing!`.
785 /// #![feature(associated_types)]
787 /// use std::ops::IndexMut;
789 /// #[deriving(Copy)]
792 /// impl IndexMut<Foo> for Foo {
793 /// type Output = Foo;
795 /// fn index_mut<'a>(&'a mut self, _index: &Foo) -> &'a mut Foo {
796 /// println!("Indexing!");
805 #[cfg(not(stage0))] // NOTE(stage0) remove cfg after a snapshot
807 pub trait IndexMut<Sized? Index> for Sized? {
810 /// The method for the indexing (`Foo[Bar]`) operation
811 fn index_mut<'a>(&'a mut self, index: &Index) -> &'a mut Self::Output;
814 /// The `Slice` trait is used to specify the functionality of slicing operations
815 /// like `arr[from..to]` when used in an immutable context.
819 /// A trivial implementation of `Slice`. When `Foo[..Foo]` happens, it ends up
820 /// calling `slice_to`, and therefore, `main` prints `Slicing!`.
823 /// use std::ops::Slice;
825 /// #[deriving(Copy)]
828 /// impl Slice<Foo, Foo> for Foo {
829 /// fn as_slice_<'a>(&'a self) -> &'a Foo {
830 /// println!("Slicing!");
833 /// fn slice_from_or_fail<'a>(&'a self, _from: &Foo) -> &'a Foo {
834 /// println!("Slicing!");
837 /// fn slice_to_or_fail<'a>(&'a self, _to: &Foo) -> &'a Foo {
838 /// println!("Slicing!");
841 /// fn slice_or_fail<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo {
842 /// println!("Slicing!");
852 pub trait Slice<Sized? Idx, Sized? Result> for Sized? {
853 /// The method for the slicing operation foo[]
854 fn as_slice_<'a>(&'a self) -> &'a Result;
855 /// The method for the slicing operation foo[from..]
856 fn slice_from_or_fail<'a>(&'a self, from: &Idx) -> &'a Result;
857 /// The method for the slicing operation foo[..to]
858 fn slice_to_or_fail<'a>(&'a self, to: &Idx) -> &'a Result;
859 /// The method for the slicing operation foo[from..to]
860 fn slice_or_fail<'a>(&'a self, from: &Idx, to: &Idx) -> &'a Result;
863 /// The `SliceMut` trait is used to specify the functionality of slicing
864 /// operations like `arr[from..to]`, when used in a mutable context.
868 /// A trivial implementation of `SliceMut`. When `Foo[Foo..]` happens, it ends up
869 /// calling `slice_from_mut`, and therefore, `main` prints `Slicing!`.
872 /// use std::ops::SliceMut;
874 /// #[deriving(Copy)]
877 /// impl SliceMut<Foo, Foo> for Foo {
878 /// fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Foo {
879 /// println!("Slicing!");
882 /// fn slice_from_or_fail_mut<'a>(&'a mut self, _from: &Foo) -> &'a mut Foo {
883 /// println!("Slicing!");
886 /// fn slice_to_or_fail_mut<'a>(&'a mut self, _to: &Foo) -> &'a mut Foo {
887 /// println!("Slicing!");
890 /// fn slice_or_fail_mut<'a>(&'a mut self, _from: &Foo, _to: &Foo) -> &'a mut Foo {
891 /// println!("Slicing!");
901 pub trait SliceMut<Sized? Idx, Sized? Result> for Sized? {
902 /// The method for the slicing operation foo[]
903 fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Result;
904 /// The method for the slicing operation foo[from..]
905 fn slice_from_or_fail_mut<'a>(&'a mut self, from: &Idx) -> &'a mut Result;
906 /// The method for the slicing operation foo[..to]
907 fn slice_to_or_fail_mut<'a>(&'a mut self, to: &Idx) -> &'a mut Result;
908 /// The method for the slicing operation foo[from..to]
909 fn slice_or_fail_mut<'a>(&'a mut self, from: &Idx, to: &Idx) -> &'a mut Result;
913 /// An unbounded range.
916 pub struct FullRange;
918 /// A (half-open) range which is bounded at both ends.
921 pub struct Range<Idx> {
922 /// The lower bound of the range (inclusive).
924 /// The upper bound of the range (exclusive).
928 // FIXME(#19391) needs a snapshot
929 //impl<Idx: Clone + Step<T=uint>> Iterator<Idx> for Range<Idx> {
930 impl<Idx: Clone + Step> Iterator for Range<Idx> {
934 fn next(&mut self) -> Option<Idx> {
935 if self.start < self.end {
936 let result = self.start.clone();
945 fn size_hint(&self) -> (uint, Option<uint>) {
946 if let Some(hint) = Step::steps_between(&self.end, &self.start) {
954 impl<Idx: Clone + Step> DoubleEndedIterator for Range<Idx> {
956 fn next_back(&mut self) -> Option<Idx> {
957 if self.start < self.end {
958 self.end.step_back();
959 return Some(self.end.clone());
966 impl<Idx: Clone + Step> ExactSizeIterator for Range<Idx> {}
968 /// A range which is only bounded below.
971 pub struct RangeFrom<Idx> {
972 /// The lower bound of the range (inclusive).
976 impl<Idx: Clone + Step> Iterator for RangeFrom<Idx> {
980 fn next(&mut self) -> Option<Idx> {
981 // Deliberately overflow so we loop forever.
982 let result = self.start.clone();
988 /// A range which is only bounded above.
991 pub struct RangeTo<Idx> {
992 /// The upper bound of the range (exclusive).
997 /// The `Deref` trait is used to specify the functionality of dereferencing
998 /// operations like `*v`.
1002 /// A struct with a single field which is accessible via dereferencing the
1006 /// #![feature(associated_types)]
1008 /// use std::ops::Deref;
1010 /// struct DerefExample<T> {
1014 /// impl<T> Deref for DerefExample<T> {
1015 /// type Target = T;
1017 /// fn deref<'a>(&'a self) -> &'a T {
1023 /// let x = DerefExample { value: 'a' };
1024 /// assert_eq!('a', *x);
1028 pub trait Deref for Sized? {
1031 /// The method called to dereference a value
1032 fn deref<'a>(&'a self) -> &'a Self::Target;
1035 impl<'a, Sized? T> Deref for &'a T {
1038 fn deref(&self) -> &T { *self }
1041 impl<'a, Sized? T> Deref for &'a mut T {
1044 fn deref(&self) -> &T { *self }
1047 /// The `DerefMut` trait is used to specify the functionality of dereferencing
1048 /// mutably like `*v = 1;`
1052 /// A struct with a single field which is modifiable via dereferencing the
1056 /// #![feature(associated_types)]
1058 /// use std::ops::{Deref, DerefMut};
1060 /// struct DerefMutExample<T> {
1064 /// impl<T> Deref for DerefMutExample<T> {
1065 /// type Target = T;
1067 /// fn deref<'a>(&'a self) -> &'a T {
1072 /// impl<T> DerefMut for DerefMutExample<T> {
1073 /// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
1079 /// let mut x = DerefMutExample { value: 'a' };
1081 /// assert_eq!('b', *x);
1085 pub trait DerefMut for Sized? : Deref {
1086 /// The method called to mutably dereference a value
1087 fn deref_mut<'a>(&'a mut self) -> &'a mut <Self as Deref>::Target;
1090 impl<'a, Sized? T> DerefMut for &'a mut T {
1091 fn deref_mut(&mut self) -> &mut T { *self }
1094 /// A version of the call operator that takes an immutable receiver.
1096 pub trait Fn<Args,Result> for Sized? {
1097 /// This is called when the call operator is used.
1098 extern "rust-call" fn call(&self, args: Args) -> Result;
1101 /// A version of the call operator that takes a mutable receiver.
1103 pub trait FnMut<Args,Result> for Sized? {
1104 /// This is called when the call operator is used.
1105 extern "rust-call" fn call_mut(&mut self, args: Args) -> Result;
1108 /// A version of the call operator that takes a by-value receiver.
1110 pub trait FnOnce<Args,Result> {
1111 /// This is called when the call operator is used.
1112 extern "rust-call" fn call_once(self, args: Args) -> Result;
1115 impl<Sized? F,A,R> FnMut<A,R> for F
1118 extern "rust-call" fn call_mut(&mut self, args: A) -> R {
1123 impl<F,A,R> FnOnce<A,R> for F
1124 where F : FnMut<A,R>
1126 extern "rust-call" fn call_once(mut self, args: A) -> R {