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(
69 on(all(_Self = "{integer}", Rhs = "{float}"), message = "cannot add a float to an integer",),
70 on(all(_Self = "{float}", Rhs = "{integer}"), message = "cannot add an integer to a float",),
71 message = "cannot add `{Rhs}` to `{Self}`",
72 label = "no implementation for `{Self} + {Rhs}`"
75 pub trait Add<Rhs = Self> {
76 /// The resulting type after applying the `+` operator.
77 #[stable(feature = "rust1", since = "1.0.0")]
80 /// Performs the `+` operation.
82 #[stable(feature = "rust1", since = "1.0.0")]
83 fn add(self, rhs: Rhs) -> Self::Output;
86 macro_rules! add_impl {
88 #[stable(feature = "rust1", since = "1.0.0")]
93 #[rustc_inherit_overflow_checks]
94 fn add(self, other: $t) -> $t { self + other }
97 forward_ref_binop! { impl Add, add for $t, $t }
101 add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
103 /// The subtraction operator `-`.
105 /// Note that `Rhs` is `Self` by default, but this is not mandatory. For
106 /// example, [`std::time::SystemTime`] implements `Sub<Duration>`, which permits
107 /// operations of the form `SystemTime = SystemTime - Duration`.
109 /// [`std::time::SystemTime`]: ../../std/time/struct.SystemTime.html
113 /// ## `Sub`tractable points
116 /// use std::ops::Sub;
118 /// #[derive(Debug, PartialEq)]
124 /// impl Sub for Point {
125 /// type Output = Point;
127 /// fn sub(self, other: Point) -> Point {
129 /// x: self.x - other.x,
130 /// y: self.y - other.y,
135 /// assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 },
136 /// Point { x: 1, y: 0 });
139 /// ## Implementing `Sub` with generics
141 /// Here is an example of the same `Point` struct implementing the `Sub` trait
145 /// use std::ops::Sub;
147 /// #[derive(Debug, PartialEq)]
148 /// struct Point<T> {
153 /// // Notice that the implementation uses the associated type `Output`.
154 /// impl<T: Sub<Output = T>> Sub for Point<T> {
155 /// type Output = Self;
157 /// fn sub(self, other: Self) -> Self::Output {
159 /// x: self.x - other.x,
160 /// y: self.y - other.y,
165 /// assert_eq!(Point { x: 2, y: 3 } - Point { x: 1, y: 0 },
166 /// Point { x: 1, y: 3 });
169 #[stable(feature = "rust1", since = "1.0.0")]
170 #[rustc_on_unimplemented(
171 message = "cannot subtract `{Rhs}` from `{Self}`",
172 label = "no implementation for `{Self} - {Rhs}`"
175 pub trait Sub<Rhs = Self> {
176 /// The resulting type after applying the `-` operator.
177 #[stable(feature = "rust1", since = "1.0.0")]
180 /// Performs the `-` operation.
182 #[stable(feature = "rust1", since = "1.0.0")]
183 fn sub(self, rhs: Rhs) -> Self::Output;
186 macro_rules! sub_impl {
188 #[stable(feature = "rust1", since = "1.0.0")]
193 #[rustc_inherit_overflow_checks]
194 fn sub(self, other: $t) -> $t { self - other }
197 forward_ref_binop! { impl Sub, sub for $t, $t }
201 sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
203 /// The multiplication operator `*`.
205 /// Note that `Rhs` is `Self` by default, but this is not mandatory.
209 /// ## `Mul`tipliable rational numbers
212 /// use std::ops::Mul;
214 /// // By the fundamental theorem of arithmetic, rational numbers in lowest
215 /// // terms are unique. So, by keeping `Rational`s in reduced form, we can
216 /// // derive `Eq` and `PartialEq`.
217 /// #[derive(Debug, Eq, PartialEq)]
218 /// struct Rational {
219 /// numerator: usize,
220 /// denominator: usize,
224 /// fn new(numerator: usize, denominator: usize) -> Self {
225 /// if denominator == 0 {
226 /// panic!("Zero is an invalid denominator!");
229 /// // Reduce to lowest terms by dividing by the greatest common
231 /// let gcd = gcd(numerator, denominator);
233 /// numerator: numerator / gcd,
234 /// denominator: denominator / gcd,
239 /// impl Mul for Rational {
240 /// // The multiplication of rational numbers is a closed operation.
241 /// type Output = Self;
243 /// fn mul(self, rhs: Self) -> Self {
244 /// let numerator = self.numerator * rhs.numerator;
245 /// let denominator = self.denominator * rhs.denominator;
246 /// Rational::new(numerator, denominator)
250 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
252 /// fn gcd(x: usize, y: usize) -> usize {
263 /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
264 /// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4),
265 /// Rational::new(1, 2));
268 /// ## Multiplying vectors by scalars as in linear algebra
271 /// use std::ops::Mul;
273 /// struct Scalar { value: usize }
275 /// #[derive(Debug, PartialEq)]
276 /// struct Vector { value: Vec<usize> }
278 /// impl Mul<Scalar> for Vector {
279 /// type Output = Self;
281 /// fn mul(self, rhs: Scalar) -> Self::Output {
282 /// Vector { value: self.value.iter().map(|v| v * rhs.value).collect() }
286 /// let vector = Vector { value: vec![2, 4, 6] };
287 /// let scalar = Scalar { value: 3 };
288 /// assert_eq!(vector * scalar, Vector { value: vec![6, 12, 18] });
291 #[stable(feature = "rust1", since = "1.0.0")]
292 #[rustc_on_unimplemented(
293 message = "cannot multiply `{Rhs}` to `{Self}`",
294 label = "no implementation for `{Self} * {Rhs}`"
297 pub trait Mul<Rhs = Self> {
298 /// The resulting type after applying the `*` operator.
299 #[stable(feature = "rust1", since = "1.0.0")]
302 /// Performs the `*` operation.
304 #[stable(feature = "rust1", since = "1.0.0")]
305 fn mul(self, rhs: Rhs) -> Self::Output;
308 macro_rules! mul_impl {
310 #[stable(feature = "rust1", since = "1.0.0")]
315 #[rustc_inherit_overflow_checks]
316 fn mul(self, other: $t) -> $t { self * other }
319 forward_ref_binop! { impl Mul, mul for $t, $t }
323 mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
325 /// The division operator `/`.
327 /// Note that `Rhs` is `Self` by default, but this is not mandatory.
331 /// ## `Div`idable rational numbers
334 /// use std::ops::Div;
336 /// // By the fundamental theorem of arithmetic, rational numbers in lowest
337 /// // terms are unique. So, by keeping `Rational`s in reduced form, we can
338 /// // derive `Eq` and `PartialEq`.
339 /// #[derive(Debug, Eq, PartialEq)]
340 /// struct Rational {
341 /// numerator: usize,
342 /// denominator: usize,
346 /// fn new(numerator: usize, denominator: usize) -> Self {
347 /// if denominator == 0 {
348 /// panic!("Zero is an invalid denominator!");
351 /// // Reduce to lowest terms by dividing by the greatest common
353 /// let gcd = gcd(numerator, denominator);
355 /// numerator: numerator / gcd,
356 /// denominator: denominator / gcd,
361 /// impl Div for Rational {
362 /// // The division of rational numbers is a closed operation.
363 /// type Output = Self;
365 /// fn div(self, rhs: Self) -> Self::Output {
366 /// if rhs.numerator == 0 {
367 /// panic!("Cannot divide by zero-valued `Rational`!");
370 /// let numerator = self.numerator * rhs.denominator;
371 /// let denominator = self.denominator * rhs.numerator;
372 /// Rational::new(numerator, denominator)
376 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
378 /// fn gcd(x: usize, y: usize) -> usize {
389 /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
390 /// assert_eq!(Rational::new(1, 2) / Rational::new(3, 4),
391 /// Rational::new(2, 3));
394 /// ## Dividing vectors by scalars as in linear algebra
397 /// use std::ops::Div;
399 /// struct Scalar { value: f32 }
401 /// #[derive(Debug, PartialEq)]
402 /// struct Vector { value: Vec<f32> }
404 /// impl Div<Scalar> for Vector {
405 /// type Output = Self;
407 /// fn div(self, rhs: Scalar) -> Self::Output {
408 /// Vector { value: self.value.iter().map(|v| v / rhs.value).collect() }
412 /// let scalar = Scalar { value: 2f32 };
413 /// let vector = Vector { value: vec![2f32, 4f32, 6f32] };
414 /// assert_eq!(vector / scalar, Vector { value: vec![1f32, 2f32, 3f32] });
417 #[stable(feature = "rust1", since = "1.0.0")]
418 #[rustc_on_unimplemented(
419 message = "cannot divide `{Self}` by `{Rhs}`",
420 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(
506 message = "cannot mod `{Self}` by `{Rhs}`",
507 label = "no implementation for `{Self} % {Rhs}`"
510 pub trait Rem<Rhs = Self> {
511 /// The resulting type after applying the `%` operator.
512 #[stable(feature = "rust1", since = "1.0.0")]
515 /// Performs the `%` operation.
517 #[stable(feature = "rust1", since = "1.0.0")]
518 fn rem(self, rhs: Rhs) -> Self::Output;
521 macro_rules! rem_impl_integer {
523 /// This operation satisfies `n % d == n - (n / d) * d`. The
524 /// result has the same sign as the left operand.
525 #[stable(feature = "rust1", since = "1.0.0")]
530 fn rem(self, other: $t) -> $t { self % other }
533 forward_ref_binop! { impl Rem, rem for $t, $t }
537 rem_impl_integer! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
539 macro_rules! rem_impl_float {
542 /// The remainder from the division of two floats.
544 /// The remainder has the same sign as the dividend and is computed as:
545 /// `x - (x / y).trunc() * y`.
549 /// let x: f32 = 50.50;
550 /// let y: f32 = 8.125;
551 /// let remainder = x - (x / y).trunc() * y;
553 /// // The answer to both operations is 1.75
554 /// assert_eq!(x % y, remainder);
556 #[stable(feature = "rust1", since = "1.0.0")]
561 fn rem(self, other: $t) -> $t { self % other }
564 forward_ref_binop! { impl Rem, rem for $t, $t }
568 rem_impl_float! { f32 f64 }
570 /// The unary negation operator `-`.
574 /// An implementation of `Neg` for `Sign`, which allows the use of `-` to
575 /// negate its value.
578 /// use std::ops::Neg;
580 /// #[derive(Debug, PartialEq)]
587 /// impl Neg for Sign {
588 /// type Output = Sign;
590 /// fn neg(self) -> Self::Output {
592 /// Sign::Negative => Sign::Positive,
593 /// Sign::Zero => Sign::Zero,
594 /// Sign::Positive => Sign::Negative,
599 /// // A negative positive is a negative.
600 /// assert_eq!(-Sign::Positive, Sign::Negative);
601 /// // A double negative is a positive.
602 /// assert_eq!(-Sign::Negative, Sign::Positive);
603 /// // Zero is its own negation.
604 /// assert_eq!(-Sign::Zero, Sign::Zero);
607 #[stable(feature = "rust1", since = "1.0.0")]
610 /// The resulting type after applying the `-` operator.
611 #[stable(feature = "rust1", since = "1.0.0")]
614 /// Performs the unary `-` operation.
616 #[stable(feature = "rust1", since = "1.0.0")]
617 fn neg(self) -> Self::Output;
620 macro_rules! neg_impl_core {
621 ($id:ident => $body:expr, $($t:ty)*) => ($(
622 #[stable(feature = "rust1", since = "1.0.0")]
627 #[rustc_inherit_overflow_checks]
628 fn neg(self) -> $t { let $id = self; $body }
631 forward_ref_unop! { impl Neg, neg for $t }
635 macro_rules! neg_impl_numeric {
636 ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} }
639 #[allow(unused_macros)]
640 macro_rules! neg_impl_unsigned {
642 neg_impl_core!{ x => {
647 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
648 neg_impl_numeric! { isize i8 i16 i32 i64 i128 f32 f64 }
650 /// The addition assignment operator `+=`.
654 /// This example creates a `Point` struct that implements the `AddAssign`
655 /// trait, and then demonstrates add-assigning to a mutable `Point`.
658 /// use std::ops::AddAssign;
660 /// #[derive(Debug, PartialEq)]
666 /// impl AddAssign for Point {
667 /// fn add_assign(&mut self, other: Self) {
669 /// x: self.x + other.x,
670 /// y: self.y + other.y,
675 /// let mut point = Point { x: 1, y: 0 };
676 /// point += Point { x: 2, y: 3 };
677 /// assert_eq!(point, Point { x: 3, y: 3 });
679 #[lang = "add_assign"]
680 #[stable(feature = "op_assign_traits", since = "1.8.0")]
681 #[rustc_on_unimplemented(
682 message = "cannot add-assign `{Rhs}` to `{Self}`",
683 label = "no implementation for `{Self} += {Rhs}`"
687 pub trait AddAssign<Rhs = Self> {
688 /// Performs the `+=` operation.
689 #[stable(feature = "op_assign_traits", since = "1.8.0")]
690 fn add_assign(&mut self, rhs: Rhs);
693 macro_rules! add_assign_impl {
695 #[stable(feature = "op_assign_traits", since = "1.8.0")]
696 impl AddAssign for $t {
698 #[rustc_inherit_overflow_checks]
699 fn add_assign(&mut self, other: $t) { *self += other }
702 forward_ref_op_assign! { impl AddAssign, add_assign for $t, $t }
706 add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
708 /// The subtraction assignment operator `-=`.
712 /// This example creates a `Point` struct that implements the `SubAssign`
713 /// trait, and then demonstrates sub-assigning to a mutable `Point`.
716 /// use std::ops::SubAssign;
718 /// #[derive(Debug, PartialEq)]
724 /// impl SubAssign for Point {
725 /// fn sub_assign(&mut self, other: Self) {
727 /// x: self.x - other.x,
728 /// y: self.y - other.y,
733 /// let mut point = Point { x: 3, y: 3 };
734 /// point -= Point { x: 2, y: 3 };
735 /// assert_eq!(point, Point {x: 1, y: 0});
737 #[lang = "sub_assign"]
738 #[stable(feature = "op_assign_traits", since = "1.8.0")]
739 #[rustc_on_unimplemented(
740 message = "cannot subtract-assign `{Rhs}` from `{Self}`",
741 label = "no implementation for `{Self} -= {Rhs}`"
745 pub trait SubAssign<Rhs = Self> {
746 /// Performs the `-=` operation.
747 #[stable(feature = "op_assign_traits", since = "1.8.0")]
748 fn sub_assign(&mut self, rhs: Rhs);
751 macro_rules! sub_assign_impl {
753 #[stable(feature = "op_assign_traits", since = "1.8.0")]
754 impl SubAssign for $t {
756 #[rustc_inherit_overflow_checks]
757 fn sub_assign(&mut self, other: $t) { *self -= other }
760 forward_ref_op_assign! { impl SubAssign, sub_assign for $t, $t }
764 sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
766 /// The multiplication assignment operator `*=`.
771 /// use std::ops::MulAssign;
773 /// #[derive(Debug, PartialEq)]
774 /// struct Frequency { hertz: f64 }
776 /// impl MulAssign<f64> for Frequency {
777 /// fn mul_assign(&mut self, rhs: f64) {
778 /// self.hertz *= rhs;
782 /// let mut frequency = Frequency { hertz: 50.0 };
783 /// frequency *= 4.0;
784 /// assert_eq!(Frequency { hertz: 200.0 }, frequency);
786 #[lang = "mul_assign"]
787 #[stable(feature = "op_assign_traits", since = "1.8.0")]
788 #[rustc_on_unimplemented(
789 message = "cannot multiply-assign `{Rhs}` to `{Self}`",
790 label = "no implementation for `{Self} *= {Rhs}`"
794 pub trait MulAssign<Rhs = Self> {
795 /// Performs the `*=` operation.
796 #[stable(feature = "op_assign_traits", since = "1.8.0")]
797 fn mul_assign(&mut self, rhs: Rhs);
800 macro_rules! mul_assign_impl {
802 #[stable(feature = "op_assign_traits", since = "1.8.0")]
803 impl MulAssign for $t {
805 #[rustc_inherit_overflow_checks]
806 fn mul_assign(&mut self, other: $t) { *self *= other }
809 forward_ref_op_assign! { impl MulAssign, mul_assign for $t, $t }
813 mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
815 /// The division assignment operator `/=`.
820 /// use std::ops::DivAssign;
822 /// #[derive(Debug, PartialEq)]
823 /// struct Frequency { hertz: f64 }
825 /// impl DivAssign<f64> for Frequency {
826 /// fn div_assign(&mut self, rhs: f64) {
827 /// self.hertz /= rhs;
831 /// let mut frequency = Frequency { hertz: 200.0 };
832 /// frequency /= 4.0;
833 /// assert_eq!(Frequency { hertz: 50.0 }, frequency);
835 #[lang = "div_assign"]
836 #[stable(feature = "op_assign_traits", since = "1.8.0")]
837 #[rustc_on_unimplemented(
838 message = "cannot divide-assign `{Self}` by `{Rhs}`",
839 label = "no implementation for `{Self} /= {Rhs}`"
843 pub trait DivAssign<Rhs = Self> {
844 /// Performs the `/=` operation.
845 #[stable(feature = "op_assign_traits", since = "1.8.0")]
846 fn div_assign(&mut self, rhs: Rhs);
849 macro_rules! div_assign_impl {
851 #[stable(feature = "op_assign_traits", since = "1.8.0")]
852 impl DivAssign for $t {
854 fn div_assign(&mut self, other: $t) { *self /= other }
857 forward_ref_op_assign! { impl DivAssign, div_assign for $t, $t }
861 div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
863 /// The remainder assignment operator `%=`.
868 /// use std::ops::RemAssign;
870 /// struct CookieJar { cookies: u32 }
872 /// impl RemAssign<u32> for CookieJar {
873 /// fn rem_assign(&mut self, piles: u32) {
874 /// self.cookies %= piles;
878 /// let mut jar = CookieJar { cookies: 31 };
881 /// println!("Splitting up {} cookies into {} even piles!", jar.cookies, piles);
885 /// println!("{} cookies remain in the cookie jar!", jar.cookies);
887 #[lang = "rem_assign"]
888 #[stable(feature = "op_assign_traits", since = "1.8.0")]
889 #[rustc_on_unimplemented(
890 message = "cannot mod-assign `{Self}` by `{Rhs}``",
891 label = "no implementation for `{Self} %= {Rhs}`"
895 pub trait RemAssign<Rhs = Self> {
896 /// Performs the `%=` operation.
897 #[stable(feature = "op_assign_traits", since = "1.8.0")]
898 fn rem_assign(&mut self, rhs: Rhs);
901 macro_rules! rem_assign_impl {
903 #[stable(feature = "op_assign_traits", since = "1.8.0")]
904 impl RemAssign for $t {
906 fn rem_assign(&mut self, other: $t) { *self %= other }
909 forward_ref_op_assign! { impl RemAssign, rem_assign for $t, $t }
913 rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }