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.
65 use iter::{Step, Iterator,DoubleEndedIterator,ExactSizeIterator};
67 use option::Option::{self, Some, None};
69 /// The `Drop` trait is used to run some code when a value goes out of scope. This
70 /// is sometimes called a 'destructor'.
74 /// A trivial implementation of `Drop`. The `drop` method is called when `_x` goes
75 /// out of scope, and therefore `main` prints `Dropping!`.
80 /// impl Drop for HasDrop {
81 /// fn drop(&mut self) {
82 /// println!("Dropping!");
93 /// The `drop` method, called when the value goes out of scope.
98 /// The `Add` trait is used to specify the functionality of `+`.
102 /// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up
103 /// calling `add`, and therefore, `main` prints `Adding!`.
106 /// #![feature(associated_types)]
108 /// use std::ops::Add;
113 /// impl Add for Foo {
114 /// type Output = Foo;
116 /// fn add(self, _rhs: Foo) -> Foo {
117 /// println!("Adding!");
128 pub trait Add<RHS=Self> {
132 /// The method for the `+` operator
134 fn add(self, rhs: RHS) -> Self::Output;
137 macro_rules! add_impl {
144 fn add(self, other: $t) -> $t { self + other }
149 add_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
151 /// The `Sub` trait is used to specify the functionality of `-`.
155 /// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up
156 /// calling `sub`, and therefore, `main` prints `Subtracting!`.
159 /// #![feature(associated_types)]
161 /// use std::ops::Sub;
166 /// impl Sub for Foo {
167 /// type Output = Foo;
169 /// fn sub(self, _rhs: Foo) -> Foo {
170 /// println!("Subtracting!");
181 pub trait Sub<RHS=Self> {
185 /// The method for the `-` operator
187 fn sub(self, rhs: RHS) -> Self::Output;
190 macro_rules! sub_impl {
197 fn sub(self, other: $t) -> $t { self - other }
202 sub_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
204 /// The `Mul` trait is used to specify the functionality of `*`.
208 /// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up
209 /// calling `mul`, and therefore, `main` prints `Multiplying!`.
212 /// #![feature(associated_types)]
214 /// use std::ops::Mul;
219 /// impl Mul for Foo {
220 /// type Output = Foo;
222 /// fn mul(self, _rhs: Foo) -> Foo {
223 /// println!("Multiplying!");
234 pub trait Mul<RHS=Self> {
238 /// The method for the `*` operator
240 fn mul(self, rhs: RHS) -> Self::Output;
243 macro_rules! mul_impl {
250 fn mul(self, other: $t) -> $t { self * other }
255 mul_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
257 /// The `Div` trait is used to specify the functionality of `/`.
261 /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up
262 /// calling `div`, and therefore, `main` prints `Dividing!`.
265 /// #![feature(associated_types)]
267 /// use std::ops::Div;
272 /// impl Div for Foo {
273 /// type Output = Foo;
275 /// fn div(self, _rhs: Foo) -> Foo {
276 /// println!("Dividing!");
287 pub trait Div<RHS=Self> {
291 /// The method for the `/` operator
293 fn div(self, rhs: RHS) -> Self::Output;
296 macro_rules! div_impl {
303 fn div(self, other: $t) -> $t { self / other }
308 div_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
310 /// The `Rem` trait is used to specify the functionality of `%`.
314 /// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up
315 /// calling `rem`, and therefore, `main` prints `Remainder-ing!`.
318 /// #![feature(associated_types)]
320 /// use std::ops::Rem;
325 /// impl Rem for Foo {
326 /// type Output = Foo;
328 /// fn rem(self, _rhs: Foo) -> Foo {
329 /// println!("Remainder-ing!");
340 pub trait Rem<RHS=Self> {
344 /// The method for the `%` operator
346 fn rem(self, rhs: RHS) -> Self::Output;
349 macro_rules! rem_impl {
356 fn rem(self, other: $t) -> $t { self % other }
361 macro_rules! rem_float_impl {
362 ($t:ty, $fmod:ident) => {
368 fn rem(self, other: $t) -> $t {
369 extern { fn $fmod(a: $t, b: $t) -> $t; }
370 unsafe { $fmod(self, other) }
376 rem_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 }
377 rem_float_impl! { f32, fmodf }
378 rem_float_impl! { f64, fmod }
380 /// The `Neg` trait is used to specify the functionality of unary `-`.
384 /// A trivial implementation of `Neg`. When `-Foo` happens, it ends up calling
385 /// `neg`, and therefore, `main` prints `Negating!`.
388 /// #![feature(associated_types)]
390 /// use std::ops::Neg;
394 /// impl Copy for Foo {}
396 /// impl Neg for Foo {
397 /// type Output = Foo;
399 /// fn neg(self) -> Foo {
400 /// println!("Negating!");
415 /// The method for the unary `-` operator
417 fn neg(self) -> Self::Output;
420 macro_rules! neg_impl {
429 fn neg(self) -> $t { -self }
434 macro_rules! neg_uint_impl {
435 ($t:ty, $t_signed:ty) => {
441 fn neg(self) -> $t { -(self as $t_signed) as $t }
446 neg_impl! { int i8 i16 i32 i64 f32 f64 }
448 neg_uint_impl! { uint, int }
449 neg_uint_impl! { u8, i8 }
450 neg_uint_impl! { u16, i16 }
451 neg_uint_impl! { u32, i32 }
452 neg_uint_impl! { u64, i64 }
455 /// The `Not` trait is used to specify the functionality of unary `!`.
459 /// A trivial implementation of `Not`. When `!Foo` happens, it ends up calling
460 /// `not`, and therefore, `main` prints `Not-ing!`.
463 /// #![feature(associated_types)]
465 /// use std::ops::Not;
469 /// impl Copy for Foo {}
471 /// impl Not for Foo {
472 /// type Output = Foo;
474 /// fn not(self) -> Foo {
475 /// println!("Not-ing!");
490 /// The method for the unary `!` operator
492 fn not(self) -> Self::Output;
495 macro_rules! not_impl {
502 fn not(self) -> $t { !self }
507 not_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 }
509 /// The `BitAnd` trait is used to specify the functionality of `&`.
513 /// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up
514 /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`.
517 /// #![feature(associated_types)]
519 /// use std::ops::BitAnd;
524 /// impl BitAnd for Foo {
525 /// type Output = Foo;
527 /// fn bitand(self, _rhs: Foo) -> Foo {
528 /// println!("Bitwise And-ing!");
539 pub trait BitAnd<RHS=Self> {
543 /// The method for the `&` operator
545 fn bitand(self, rhs: RHS) -> Self::Output;
548 macro_rules! bitand_impl {
555 fn bitand(self, rhs: $t) -> $t { self & rhs }
560 bitand_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 }
562 /// The `BitOr` trait is used to specify the functionality of `|`.
566 /// A trivial implementation of `BitOr`. When `Foo | Foo` happens, it ends up
567 /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`.
570 /// #![feature(associated_types)]
572 /// use std::ops::BitOr;
577 /// impl BitOr for Foo {
578 /// type Output = Foo;
580 /// fn bitor(self, _rhs: Foo) -> Foo {
581 /// println!("Bitwise Or-ing!");
592 pub trait BitOr<RHS=Self> {
596 /// The method for the `|` operator
598 fn bitor(self, rhs: RHS) -> Self::Output;
601 macro_rules! bitor_impl {
608 fn bitor(self, rhs: $t) -> $t { self | rhs }
613 bitor_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 }
615 /// The `BitXor` trait is used to specify the functionality of `^`.
619 /// A trivial implementation of `BitXor`. When `Foo ^ Foo` happens, it ends up
620 /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`.
623 /// #![feature(associated_types)]
625 /// use std::ops::BitXor;
630 /// impl BitXor for Foo {
631 /// type Output = Foo;
633 /// fn bitxor(self, _rhs: Foo) -> Foo {
634 /// println!("Bitwise Xor-ing!");
645 pub trait BitXor<RHS=Self> {
649 /// The method for the `^` operator
651 fn bitxor(self, rhs: RHS) -> Self::Output;
654 macro_rules! bitxor_impl {
661 fn bitxor(self, other: $t) -> $t { self ^ other }
666 bitxor_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 }
668 /// The `Shl` trait is used to specify the functionality of `<<`.
672 /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up
673 /// calling `shl`, and therefore, `main` prints `Shifting left!`.
676 /// #![feature(associated_types)]
678 /// use std::ops::Shl;
683 /// impl Shl<Foo> for Foo {
684 /// type Output = Foo;
686 /// fn shl(self, _rhs: Foo) -> Foo {
687 /// println!("Shifting left!");
702 /// The method for the `<<` operator
704 fn shl(self, rhs: RHS) -> Self::Output;
707 macro_rules! shl_impl {
710 impl Shl<uint> for $t {
714 fn shl(self, other: uint) -> $t {
721 shl_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 }
723 /// The `Shr` trait is used to specify the functionality of `>>`.
727 /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up
728 /// calling `shr`, and therefore, `main` prints `Shifting right!`.
731 /// #![feature(associated_types)]
733 /// use std::ops::Shr;
738 /// impl Shr<Foo> for Foo {
739 /// type Output = Foo;
741 /// fn shr(self, _rhs: Foo) -> Foo {
742 /// println!("Shifting right!");
757 /// The method for the `>>` operator
759 fn shr(self, rhs: RHS) -> Self::Output;
762 macro_rules! shr_impl {
764 impl Shr<uint> for $t {
768 fn shr(self, other: uint) -> $t { self >> other }
773 shr_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 }
775 /// The `Index` trait is used to specify the functionality of indexing operations
776 /// like `arr[idx]` when used in an immutable context.
780 /// A trivial implementation of `Index`. When `Foo[Foo]` happens, it ends up
781 /// calling `index`, and therefore, `main` prints `Indexing!`.
784 /// #![feature(associated_types)]
786 /// use std::ops::Index;
791 /// impl Index<Foo> for Foo {
792 /// type Output = Foo;
794 /// fn index<'a>(&'a self, _index: &Foo) -> &'a Foo {
795 /// println!("Indexing!");
805 pub trait Index<Index: ?Sized> {
808 /// The method for the indexing (`Foo[Bar]`) operation
809 fn index<'a>(&'a self, index: &Index) -> &'a Self::Output;
812 /// The `IndexMut` trait is used to specify the functionality of indexing
813 /// operations like `arr[idx]`, when used in a mutable context.
817 /// A trivial implementation of `IndexMut`. When `Foo[Foo]` happens, it ends up
818 /// calling `index_mut`, and therefore, `main` prints `Indexing!`.
821 /// #![feature(associated_types)]
823 /// use std::ops::IndexMut;
828 /// impl IndexMut<Foo> for Foo {
829 /// type Output = Foo;
831 /// fn index_mut<'a>(&'a mut self, _index: &Foo) -> &'a mut Foo {
832 /// println!("Indexing!");
842 pub trait IndexMut<Index: ?Sized> {
845 /// The method for the indexing (`Foo[Bar]`) operation
846 fn index_mut<'a>(&'a mut self, index: &Index) -> &'a mut Self::Output;
849 /// The `Slice` trait is used to specify the functionality of slicing operations
850 /// like `arr[from..to]` when used in an immutable context.
854 /// A trivial implementation of `Slice`. When `Foo[..Foo]` happens, it ends up
855 /// calling `slice_to`, and therefore, `main` prints `Slicing!`.
858 /// use std::ops::Slice;
863 /// impl Slice<Foo, Foo> for Foo {
864 /// fn as_slice_<'a>(&'a self) -> &'a Foo {
865 /// println!("Slicing!");
868 /// fn slice_from_or_fail<'a>(&'a self, _from: &Foo) -> &'a Foo {
869 /// println!("Slicing!");
872 /// fn slice_to_or_fail<'a>(&'a self, _to: &Foo) -> &'a Foo {
873 /// println!("Slicing!");
876 /// fn slice_or_fail<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo {
877 /// println!("Slicing!");
887 pub trait Slice<Idx: ?Sized, Result: ?Sized> {
888 /// The method for the slicing operation foo[]
889 fn as_slice_<'a>(&'a self) -> &'a Result;
890 /// The method for the slicing operation foo[from..]
891 fn slice_from_or_fail<'a>(&'a self, from: &Idx) -> &'a Result;
892 /// The method for the slicing operation foo[..to]
893 fn slice_to_or_fail<'a>(&'a self, to: &Idx) -> &'a Result;
894 /// The method for the slicing operation foo[from..to]
895 fn slice_or_fail<'a>(&'a self, from: &Idx, to: &Idx) -> &'a Result;
898 /// The `SliceMut` trait is used to specify the functionality of slicing
899 /// operations like `arr[from..to]`, when used in a mutable context.
903 /// A trivial implementation of `SliceMut`. When `Foo[Foo..]` happens, it ends up
904 /// calling `slice_from_mut`, and therefore, `main` prints `Slicing!`.
907 /// use std::ops::SliceMut;
912 /// impl SliceMut<Foo, Foo> for Foo {
913 /// fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Foo {
914 /// println!("Slicing!");
917 /// fn slice_from_or_fail_mut<'a>(&'a mut self, _from: &Foo) -> &'a mut Foo {
918 /// println!("Slicing!");
921 /// fn slice_to_or_fail_mut<'a>(&'a mut self, _to: &Foo) -> &'a mut Foo {
922 /// println!("Slicing!");
925 /// fn slice_or_fail_mut<'a>(&'a mut self, _from: &Foo, _to: &Foo) -> &'a mut Foo {
926 /// println!("Slicing!");
936 pub trait SliceMut<Idx: ?Sized, Result: ?Sized> {
937 /// The method for the slicing operation foo[]
938 fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Result;
939 /// The method for the slicing operation foo[from..]
940 fn slice_from_or_fail_mut<'a>(&'a mut self, from: &Idx) -> &'a mut Result;
941 /// The method for the slicing operation foo[..to]
942 fn slice_to_or_fail_mut<'a>(&'a mut self, to: &Idx) -> &'a mut Result;
943 /// The method for the slicing operation foo[from..to]
944 fn slice_or_fail_mut<'a>(&'a mut self, from: &Idx, to: &Idx) -> &'a mut Result;
948 /// An unbounded range.
951 #[unstable = "API still in development"]
952 pub struct FullRange;
954 /// A (half-open) range which is bounded at both ends.
957 #[unstable = "API still in development"]
958 pub struct Range<Idx> {
959 /// The lower bound of the range (inclusive).
961 /// The upper bound of the range (exclusive).
965 // FIXME(#19391) needs a snapshot
966 //impl<Idx: Clone + Step<T=uint>> Iterator<Idx> for Range<Idx> {
967 #[unstable = "API still in development"]
968 impl<Idx: Clone + Step> Iterator for Range<Idx> {
972 fn next(&mut self) -> Option<Idx> {
973 if self.start < self.end {
974 let result = self.start.clone();
983 fn size_hint(&self) -> (uint, Option<uint>) {
984 if let Some(hint) = Step::steps_between(&self.start, &self.end) {
992 #[unstable = "API still in development"]
993 impl<Idx: Clone + Step> DoubleEndedIterator for Range<Idx> {
995 fn next_back(&mut self) -> Option<Idx> {
996 if self.start < self.end {
997 self.end.step_back();
998 return Some(self.end.clone());
1005 #[unstable = "API still in development"]
1006 impl<Idx: Clone + Step> ExactSizeIterator for Range<Idx> {}
1008 /// A range which is only bounded below.
1010 #[lang="range_from"]
1011 #[unstable = "API still in development"]
1012 pub struct RangeFrom<Idx> {
1013 /// The lower bound of the range (inclusive).
1017 #[unstable = "API still in development"]
1018 impl<Idx: Clone + Step> Iterator for RangeFrom<Idx> {
1022 fn next(&mut self) -> Option<Idx> {
1023 // Deliberately overflow so we loop forever.
1024 let result = self.start.clone();
1026 return Some(result);
1030 /// A range which is only bounded above.
1033 #[unstable = "API still in development"]
1034 pub struct RangeTo<Idx> {
1035 /// The upper bound of the range (exclusive).
1040 /// The `Deref` trait is used to specify the functionality of dereferencing
1041 /// operations like `*v`.
1045 /// A struct with a single field which is accessible via dereferencing the
1049 /// #![feature(associated_types)]
1051 /// use std::ops::Deref;
1053 /// struct DerefExample<T> {
1057 /// impl<T> Deref for DerefExample<T> {
1058 /// type Target = T;
1060 /// fn deref<'a>(&'a self) -> &'a T {
1066 /// let x = DerefExample { value: 'a' };
1067 /// assert_eq!('a', *x);
1074 type Target: ?Sized;
1076 /// The method called to dereference a value
1078 fn deref<'a>(&'a self) -> &'a Self::Target;
1082 impl<'a, T: ?Sized> Deref for &'a T {
1085 fn deref(&self) -> &T { *self }
1089 impl<'a, T: ?Sized> Deref for &'a mut T {
1092 fn deref(&self) -> &T { *self }
1095 /// The `DerefMut` trait is used to specify the functionality of dereferencing
1096 /// mutably like `*v = 1;`
1100 /// A struct with a single field which is modifiable via dereferencing the
1104 /// #![feature(associated_types)]
1106 /// use std::ops::{Deref, DerefMut};
1108 /// struct DerefMutExample<T> {
1112 /// impl<T> Deref for DerefMutExample<T> {
1113 /// type Target = T;
1115 /// fn deref<'a>(&'a self) -> &'a T {
1120 /// impl<T> DerefMut for DerefMutExample<T> {
1121 /// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
1127 /// let mut x = DerefMutExample { value: 'a' };
1129 /// assert_eq!('b', *x);
1134 pub trait DerefMut: Deref {
1135 /// The method called to mutably dereference a value
1137 fn deref_mut<'a>(&'a mut self) -> &'a mut <Self as Deref>::Target;
1141 impl<'a, T: ?Sized> DerefMut for &'a mut T {
1142 fn deref_mut(&mut self) -> &mut T { *self }
1145 /// A version of the call operator that takes an immutable receiver.
1147 #[unstable = "uncertain about variadic generics, input versus associated types"]
1148 pub trait Fn<Args,Result> {
1149 /// This is called when the call operator is used.
1150 extern "rust-call" fn call(&self, args: Args) -> Result;
1153 /// A version of the call operator that takes a mutable receiver.
1155 #[unstable = "uncertain about variadic generics, input versus associated types"]
1156 pub trait FnMut<Args,Result> {
1157 /// This is called when the call operator is used.
1158 extern "rust-call" fn call_mut(&mut self, args: Args) -> Result;
1161 /// A version of the call operator that takes a by-value receiver.
1163 #[unstable = "uncertain about variadic generics, input versus associated types"]
1164 pub trait FnOnce<Args,Result> {
1165 /// This is called when the call operator is used.
1166 extern "rust-call" fn call_once(self, args: Args) -> Result;
1169 impl<F: ?Sized, A, R> FnMut<A, R> for F
1172 extern "rust-call" fn call_mut(&mut self, args: A) -> R {
1177 impl<F,A,R> FnOnce<A,R> for F
1178 where F : FnMut<A,R>
1180 extern "rust-call" fn call_once(mut self, args: A) -> R {