1 /// The addition operator `+`.
3 /// Note that `Rhs` is `Self` by default, but this is not mandatory. For
4 /// example, [`std::time::SystemTime`] implements `Add<Duration>`, which permits
5 /// operations of the form `SystemTime = SystemTime + Duration`.
7 /// [`std::time::SystemTime`]: ../../std/time/struct.SystemTime.html
11 /// ## `Add`able points
14 /// use std::ops::Add;
16 /// #[derive(Debug, PartialEq)]
22 /// impl Add for Point {
23 /// type Output = Self;
25 /// fn add(self, other: Self) -> Self {
27 /// x: self.x + other.x,
28 /// y: self.y + other.y,
33 /// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
34 /// Point { x: 3, y: 3 });
37 /// ## Implementing `Add` with generics
39 /// Here is an example of the same `Point` struct implementing the `Add` trait
43 /// use std::ops::Add;
45 /// #[derive(Debug, PartialEq)]
51 /// // Notice that the implementation uses the associated type `Output`.
52 /// impl<T: Add<Output = T>> Add for Point<T> {
53 /// type Output = Self;
55 /// fn add(self, other: Self) -> Self::Output {
57 /// x: self.x + other.x,
58 /// y: self.y + other.y,
63 /// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
64 /// Point { x: 3, y: 3 });
67 #[stable(feature = "rust1", since = "1.0.0")]
68 #[rustc_on_unimplemented(
70 all(_Self="{integer}", Rhs="{float}"),
71 message="cannot add a float to an integer",
74 all(_Self="{float}", Rhs="{integer}"),
75 message="cannot add an integer to a float",
77 message="cannot add `{Rhs}` to `{Self}`",
78 label="no implementation for `{Self} + {Rhs}`",
81 pub trait Add<Rhs=Self> {
82 /// The resulting type after applying the `+` operator.
83 #[stable(feature = "rust1", since = "1.0.0")]
86 /// Performs the `+` operation.
88 #[stable(feature = "rust1", since = "1.0.0")]
89 fn add(self, rhs: Rhs) -> Self::Output;
92 macro_rules! add_impl {
94 #[stable(feature = "rust1", since = "1.0.0")]
99 #[rustc_inherit_overflow_checks]
100 fn add(self, other: $t) -> $t { self + other }
103 forward_ref_binop! { impl Add, add for $t, $t }
107 add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
109 /// The subtraction operator `-`.
111 /// Note that `Rhs` is `Self` by default, but this is not mandatory. For
112 /// example, [`std::time::SystemTime`] implements `Sub<Duration>`, which permits
113 /// operations of the form `SystemTime = SystemTime - Duration`.
115 /// [`std::time::SystemTime`]: ../../std/time/struct.SystemTime.html
119 /// ## `Sub`tractable points
122 /// use std::ops::Sub;
124 /// #[derive(Debug, PartialEq)]
130 /// impl Sub for Point {
131 /// type Output = Point;
133 /// fn sub(self, other: Point) -> Point {
135 /// x: self.x - other.x,
136 /// y: self.y - other.y,
141 /// assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 },
142 /// Point { x: 1, y: 0 });
145 /// ## Implementing `Sub` with generics
147 /// Here is an example of the same `Point` struct implementing the `Sub` trait
151 /// use std::ops::Sub;
153 /// #[derive(Debug, PartialEq)]
154 /// struct Point<T> {
159 /// // Notice that the implementation uses the associated type `Output`.
160 /// impl<T: Sub<Output = T>> Sub for Point<T> {
161 /// type Output = Self;
163 /// fn sub(self, other: Self) -> Self::Output {
165 /// x: self.x - other.x,
166 /// y: self.y - other.y,
171 /// assert_eq!(Point { x: 2, y: 3 } - Point { x: 1, y: 0 },
172 /// Point { x: 1, y: 3 });
175 #[stable(feature = "rust1", since = "1.0.0")]
176 #[rustc_on_unimplemented(message="cannot subtract `{Rhs}` from `{Self}`",
177 label="no implementation for `{Self} - {Rhs}`")]
179 pub trait Sub<Rhs=Self> {
180 /// The resulting type after applying the `-` operator.
181 #[stable(feature = "rust1", since = "1.0.0")]
184 /// Performs the `-` operation.
186 #[stable(feature = "rust1", since = "1.0.0")]
187 fn sub(self, rhs: Rhs) -> Self::Output;
190 macro_rules! sub_impl {
192 #[stable(feature = "rust1", since = "1.0.0")]
197 #[rustc_inherit_overflow_checks]
198 fn sub(self, other: $t) -> $t { self - other }
201 forward_ref_binop! { impl Sub, sub for $t, $t }
205 sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
207 /// The multiplication operator `*`.
209 /// Note that `Rhs` is `Self` by default, but this is not mandatory.
213 /// ## `Mul`tipliable rational numbers
216 /// use std::ops::Mul;
218 /// // By the fundamental theorem of arithmetic, rational numbers in lowest
219 /// // terms are unique. So, by keeping `Rational`s in reduced form, we can
220 /// // derive `Eq` and `PartialEq`.
221 /// #[derive(Debug, Eq, PartialEq)]
222 /// struct Rational {
223 /// numerator: usize,
224 /// denominator: usize,
228 /// fn new(numerator: usize, denominator: usize) -> Self {
229 /// if denominator == 0 {
230 /// panic!("Zero is an invalid denominator!");
233 /// // Reduce to lowest terms by dividing by the greatest common
235 /// let gcd = gcd(numerator, denominator);
237 /// numerator: numerator / gcd,
238 /// denominator: denominator / gcd,
243 /// impl Mul for Rational {
244 /// // The multiplication of rational numbers is a closed operation.
245 /// type Output = Self;
247 /// fn mul(self, rhs: Self) -> Self {
248 /// let numerator = self.numerator * rhs.numerator;
249 /// let denominator = self.denominator * rhs.denominator;
250 /// Rational::new(numerator, denominator)
254 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
256 /// fn gcd(x: usize, y: usize) -> usize {
267 /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
268 /// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4),
269 /// Rational::new(1, 2));
272 /// ## Multiplying vectors by scalars as in linear algebra
275 /// use std::ops::Mul;
277 /// struct Scalar { value: usize }
279 /// #[derive(Debug, PartialEq)]
280 /// struct Vector { value: Vec<usize> }
282 /// impl Mul<Scalar> for Vector {
283 /// type Output = Self;
285 /// fn mul(self, rhs: Scalar) -> Self::Output {
286 /// Vector { value: self.value.iter().map(|v| v * rhs.value).collect() }
290 /// let vector = Vector { value: vec![2, 4, 6] };
291 /// let scalar = Scalar { value: 3 };
292 /// assert_eq!(vector * scalar, Vector { value: vec![6, 12, 18] });
295 #[stable(feature = "rust1", since = "1.0.0")]
296 #[rustc_on_unimplemented(message="cannot multiply `{Rhs}` to `{Self}`",
297 label="no implementation for `{Self} * {Rhs}`")]
299 pub trait Mul<Rhs=Self> {
300 /// The resulting type after applying the `*` operator.
301 #[stable(feature = "rust1", since = "1.0.0")]
304 /// Performs the `*` operation.
306 #[stable(feature = "rust1", since = "1.0.0")]
307 fn mul(self, rhs: Rhs) -> Self::Output;
310 macro_rules! mul_impl {
312 #[stable(feature = "rust1", since = "1.0.0")]
317 #[rustc_inherit_overflow_checks]
318 fn mul(self, other: $t) -> $t { self * other }
321 forward_ref_binop! { impl Mul, mul for $t, $t }
325 mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
327 /// The division operator `/`.
329 /// Note that `Rhs` is `Self` by default, but this is not mandatory.
333 /// ## `Div`idable rational numbers
336 /// use std::ops::Div;
338 /// // By the fundamental theorem of arithmetic, rational numbers in lowest
339 /// // terms are unique. So, by keeping `Rational`s in reduced form, we can
340 /// // derive `Eq` and `PartialEq`.
341 /// #[derive(Debug, Eq, PartialEq)]
342 /// struct Rational {
343 /// numerator: usize,
344 /// denominator: usize,
348 /// fn new(numerator: usize, denominator: usize) -> Self {
349 /// if denominator == 0 {
350 /// panic!("Zero is an invalid denominator!");
353 /// // Reduce to lowest terms by dividing by the greatest common
355 /// let gcd = gcd(numerator, denominator);
357 /// numerator: numerator / gcd,
358 /// denominator: denominator / gcd,
363 /// impl Div for Rational {
364 /// // The division of rational numbers is a closed operation.
365 /// type Output = Self;
367 /// fn div(self, rhs: Self) -> Self::Output {
368 /// if rhs.numerator == 0 {
369 /// panic!("Cannot divide by zero-valued `Rational`!");
372 /// let numerator = self.numerator * rhs.denominator;
373 /// let denominator = self.denominator * rhs.numerator;
374 /// Rational::new(numerator, denominator)
378 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
380 /// fn gcd(x: usize, y: usize) -> usize {
391 /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
392 /// assert_eq!(Rational::new(1, 2) / Rational::new(3, 4),
393 /// Rational::new(2, 3));
396 /// ## Dividing vectors by scalars as in linear algebra
399 /// use std::ops::Div;
401 /// struct Scalar { value: f32 }
403 /// #[derive(Debug, PartialEq)]
404 /// struct Vector { value: Vec<f32> }
406 /// impl Div<Scalar> for Vector {
407 /// type Output = Self;
409 /// fn div(self, rhs: Scalar) -> Self::Output {
410 /// Vector { value: self.value.iter().map(|v| v / rhs.value).collect() }
414 /// let scalar = Scalar { value: 2f32 };
415 /// let vector = Vector { value: vec![2f32, 4f32, 6f32] };
416 /// assert_eq!(vector / scalar, Vector { value: vec![1f32, 2f32, 3f32] });
419 #[stable(feature = "rust1", since = "1.0.0")]
420 #[rustc_on_unimplemented(message="cannot divide `{Self}` by `{Rhs}`",
421 label="no implementation for `{Self} / {Rhs}`")]
423 pub trait Div<Rhs=Self> {
424 /// The resulting type after applying the `/` operator.
425 #[stable(feature = "rust1", since = "1.0.0")]
428 /// Performs the `/` operation.
430 #[stable(feature = "rust1", since = "1.0.0")]
431 fn div(self, rhs: Rhs) -> Self::Output;
434 macro_rules! div_impl_integer {
436 /// This operation rounds towards zero, truncating any
437 /// fractional part of the exact result.
438 #[stable(feature = "rust1", since = "1.0.0")]
443 fn div(self, other: $t) -> $t { self / other }
446 forward_ref_binop! { impl Div, div for $t, $t }
450 div_impl_integer! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
452 macro_rules! div_impl_float {
454 #[stable(feature = "rust1", since = "1.0.0")]
459 fn div(self, other: $t) -> $t { self / other }
462 forward_ref_binop! { impl Div, div for $t, $t }
466 div_impl_float! { f32 f64 }
468 /// The remainder operator `%`.
470 /// Note that `Rhs` is `Self` by default, but this is not mandatory.
474 /// This example implements `Rem` on a `SplitSlice` object. After `Rem` is
475 /// implemented, one can use the `%` operator to find out what the remaining
476 /// elements of the slice would be after splitting it into equal slices of a
480 /// use std::ops::Rem;
482 /// #[derive(PartialEq, Debug)]
483 /// struct SplitSlice<'a, T: 'a> {
487 /// impl<'a, T> Rem<usize> for SplitSlice<'a, T> {
488 /// type Output = Self;
490 /// fn rem(self, modulus: usize) -> Self::Output {
491 /// let len = self.slice.len();
492 /// let rem = len % modulus;
493 /// let start = len - rem;
494 /// SplitSlice {slice: &self.slice[start..]}
498 /// // If we were to divide &[0, 1, 2, 3, 4, 5, 6, 7] into slices of size 3,
499 /// // the remainder would be &[6, 7].
500 /// assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3,
501 /// SplitSlice { slice: &[6, 7] });
504 #[stable(feature = "rust1", since = "1.0.0")]
505 #[rustc_on_unimplemented(message="cannot mod `{Self}` by `{Rhs}`",
506 label="no implementation for `{Self} % {Rhs}`")]
508 pub trait Rem<Rhs=Self> {
509 /// The resulting type after applying the `%` operator.
510 #[stable(feature = "rust1", since = "1.0.0")]
513 /// Performs the `%` operation.
515 #[stable(feature = "rust1", since = "1.0.0")]
516 fn rem(self, rhs: Rhs) -> Self::Output;
519 macro_rules! rem_impl_integer {
521 /// This operation satisfies `n % d == n - (n / d) * d`. The
522 /// result has the same sign as the left operand.
523 #[stable(feature = "rust1", since = "1.0.0")]
528 fn rem(self, other: $t) -> $t { self % other }
531 forward_ref_binop! { impl Rem, rem for $t, $t }
535 rem_impl_integer! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
538 macro_rules! rem_impl_float {
541 /// The remainder from the division of two floats.
543 /// The remainder has the same sign as the dividend and is computed as:
544 /// `x - (x / y).trunc() * y`.
548 /// let x: f32 = 50.50;
549 /// let y: f32 = 8.125;
550 /// let remainder = x - (x / y).trunc() * y;
552 /// // The answer to both operations is 1.75
553 /// assert_eq!(x % y, remainder);
555 #[stable(feature = "rust1", since = "1.0.0")]
560 fn rem(self, other: $t) -> $t { self % other }
563 forward_ref_binop! { impl Rem, rem for $t, $t }
567 rem_impl_float! { f32 f64 }
569 /// The unary negation operator `-`.
573 /// An implementation of `Neg` for `Sign`, which allows the use of `-` to
574 /// negate its value.
577 /// use std::ops::Neg;
579 /// #[derive(Debug, PartialEq)]
586 /// impl Neg for Sign {
587 /// type Output = Sign;
589 /// fn neg(self) -> Self::Output {
591 /// Sign::Negative => Sign::Positive,
592 /// Sign::Zero => Sign::Zero,
593 /// Sign::Positive => Sign::Negative,
598 /// // A negative positive is a negative.
599 /// assert_eq!(-Sign::Positive, Sign::Negative);
600 /// // A double negative is a positive.
601 /// assert_eq!(-Sign::Negative, Sign::Positive);
602 /// // Zero is its own negation.
603 /// assert_eq!(-Sign::Zero, Sign::Zero);
606 #[stable(feature = "rust1", since = "1.0.0")]
609 /// The resulting type after applying the `-` operator.
610 #[stable(feature = "rust1", since = "1.0.0")]
613 /// Performs the unary `-` operation.
615 #[stable(feature = "rust1", since = "1.0.0")]
616 fn neg(self) -> Self::Output;
621 macro_rules! neg_impl_core {
622 ($id:ident => $body:expr, $($t:ty)*) => ($(
623 #[stable(feature = "rust1", since = "1.0.0")]
628 #[rustc_inherit_overflow_checks]
629 fn neg(self) -> $t { let $id = self; $body }
632 forward_ref_unop! { impl Neg, neg for $t }
636 macro_rules! neg_impl_numeric {
637 ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} }
640 #[allow(unused_macros)]
641 macro_rules! neg_impl_unsigned {
643 neg_impl_core!{ x => {
648 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
649 neg_impl_numeric! { isize i8 i16 i32 i64 i128 f32 f64 }
651 /// The addition assignment operator `+=`.
655 /// This example creates a `Point` struct that implements the `AddAssign`
656 /// trait, and then demonstrates add-assigning to a mutable `Point`.
659 /// use std::ops::AddAssign;
661 /// #[derive(Debug, PartialEq)]
667 /// impl AddAssign for Point {
668 /// fn add_assign(&mut self, other: Self) {
670 /// x: self.x + other.x,
671 /// y: self.y + other.y,
676 /// let mut point = Point { x: 1, y: 0 };
677 /// point += Point { x: 2, y: 3 };
678 /// assert_eq!(point, Point { x: 3, y: 3 });
680 #[lang = "add_assign"]
681 #[stable(feature = "op_assign_traits", since = "1.8.0")]
682 #[rustc_on_unimplemented(message="cannot add-assign `{Rhs}` to `{Self}`",
683 label="no implementation for `{Self} += {Rhs}`")]
686 pub trait AddAssign<Rhs=Self> {
687 /// Performs the `+=` operation.
688 #[stable(feature = "op_assign_traits", since = "1.8.0")]
689 fn add_assign(&mut self, rhs: Rhs);
692 macro_rules! add_assign_impl {
694 #[stable(feature = "op_assign_traits", since = "1.8.0")]
695 impl AddAssign for $t {
697 #[rustc_inherit_overflow_checks]
698 fn add_assign(&mut self, other: $t) { *self += other }
701 forward_ref_op_assign! { impl AddAssign, add_assign for $t, $t }
705 add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
707 /// The subtraction assignment operator `-=`.
711 /// This example creates a `Point` struct that implements the `SubAssign`
712 /// trait, and then demonstrates sub-assigning to a mutable `Point`.
715 /// use std::ops::SubAssign;
717 /// #[derive(Debug, PartialEq)]
723 /// impl SubAssign for Point {
724 /// fn sub_assign(&mut self, other: Self) {
726 /// x: self.x - other.x,
727 /// y: self.y - other.y,
732 /// let mut point = Point { x: 3, y: 3 };
733 /// point -= Point { x: 2, y: 3 };
734 /// assert_eq!(point, Point {x: 1, y: 0});
736 #[lang = "sub_assign"]
737 #[stable(feature = "op_assign_traits", since = "1.8.0")]
738 #[rustc_on_unimplemented(message="cannot subtract-assign `{Rhs}` from `{Self}`",
739 label="no implementation for `{Self} -= {Rhs}`")]
742 pub trait SubAssign<Rhs=Self> {
743 /// Performs the `-=` operation.
744 #[stable(feature = "op_assign_traits", since = "1.8.0")]
745 fn sub_assign(&mut self, rhs: Rhs);
748 macro_rules! sub_assign_impl {
750 #[stable(feature = "op_assign_traits", since = "1.8.0")]
751 impl SubAssign for $t {
753 #[rustc_inherit_overflow_checks]
754 fn sub_assign(&mut self, other: $t) { *self -= other }
757 forward_ref_op_assign! { impl SubAssign, sub_assign for $t, $t }
761 sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
763 /// The multiplication assignment operator `*=`.
768 /// use std::ops::MulAssign;
770 /// #[derive(Debug, PartialEq)]
771 /// struct Frequency { hertz: f64 }
773 /// impl MulAssign<f64> for Frequency {
774 /// fn mul_assign(&mut self, rhs: f64) {
775 /// self.hertz *= rhs;
779 /// let mut frequency = Frequency { hertz: 50.0 };
780 /// frequency *= 4.0;
781 /// assert_eq!(Frequency { hertz: 200.0 }, frequency);
783 #[lang = "mul_assign"]
784 #[stable(feature = "op_assign_traits", since = "1.8.0")]
785 #[rustc_on_unimplemented(message="cannot multiply-assign `{Rhs}` to `{Self}`",
786 label="no implementation for `{Self} *= {Rhs}`")]
789 pub trait MulAssign<Rhs=Self> {
790 /// Performs the `*=` operation.
791 #[stable(feature = "op_assign_traits", since = "1.8.0")]
792 fn mul_assign(&mut self, rhs: Rhs);
795 macro_rules! mul_assign_impl {
797 #[stable(feature = "op_assign_traits", since = "1.8.0")]
798 impl MulAssign for $t {
800 #[rustc_inherit_overflow_checks]
801 fn mul_assign(&mut self, other: $t) { *self *= other }
804 forward_ref_op_assign! { impl MulAssign, mul_assign for $t, $t }
808 mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
810 /// The division assignment operator `/=`.
815 /// use std::ops::DivAssign;
817 /// #[derive(Debug, PartialEq)]
818 /// struct Frequency { hertz: f64 }
820 /// impl DivAssign<f64> for Frequency {
821 /// fn div_assign(&mut self, rhs: f64) {
822 /// self.hertz /= rhs;
826 /// let mut frequency = Frequency { hertz: 200.0 };
827 /// frequency /= 4.0;
828 /// assert_eq!(Frequency { hertz: 50.0 }, frequency);
830 #[lang = "div_assign"]
831 #[stable(feature = "op_assign_traits", since = "1.8.0")]
832 #[rustc_on_unimplemented(message="cannot divide-assign `{Self}` by `{Rhs}`",
833 label="no implementation for `{Self} /= {Rhs}`")]
836 pub trait DivAssign<Rhs=Self> {
837 /// Performs the `/=` operation.
838 #[stable(feature = "op_assign_traits", since = "1.8.0")]
839 fn div_assign(&mut self, rhs: Rhs);
842 macro_rules! div_assign_impl {
844 #[stable(feature = "op_assign_traits", since = "1.8.0")]
845 impl DivAssign for $t {
847 fn div_assign(&mut self, other: $t) { *self /= other }
850 forward_ref_op_assign! { impl DivAssign, div_assign for $t, $t }
854 div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
856 /// The remainder assignment operator `%=`.
861 /// use std::ops::RemAssign;
863 /// struct CookieJar { cookies: u32 }
865 /// impl RemAssign<u32> for CookieJar {
866 /// fn rem_assign(&mut self, piles: u32) {
867 /// self.cookies %= piles;
871 /// let mut jar = CookieJar { cookies: 31 };
874 /// println!("Splitting up {} cookies into {} even piles!", jar.cookies, piles);
878 /// println!("{} cookies remain in the cookie jar!", jar.cookies);
880 #[lang = "rem_assign"]
881 #[stable(feature = "op_assign_traits", since = "1.8.0")]
882 #[rustc_on_unimplemented(message="cannot mod-assign `{Self}` by `{Rhs}``",
883 label="no implementation for `{Self} %= {Rhs}`")]
886 pub trait RemAssign<Rhs=Self> {
887 /// Performs the `%=` operation.
888 #[stable(feature = "op_assign_traits", since = "1.8.0")]
889 fn rem_assign(&mut self, rhs: Rhs);
892 macro_rules! rem_assign_impl {
894 #[stable(feature = "op_assign_traits", since = "1.8.0")]
895 impl RemAssign for $t {
897 fn rem_assign(&mut self, other: $t) { *self %= other }
900 forward_ref_op_assign! { impl RemAssign, rem_assign for $t, $t }
904 rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }