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 overload certain operators.
15 //! Some of these traits are imported by the prelude, so they are available in
16 //! every Rust program. Only operators backed by traits can be overloaded. For
17 //! example, the addition operator (`+`) can be overloaded through the [`Add`]
18 //! trait, but since the assignment operator (`=`) has no backing trait, there
19 //! is no way of overloading its semantics. Additionally, this module does not
20 //! provide any mechanism to create new operators. If traitless overloading or
21 //! custom operators are required, you should look toward macros or compiler
22 //! plugins to extend Rust's syntax.
24 //! Note that the `&&` and `||` operators short-circuit, i.e. they only
25 //! evaluate their second operand if it contributes to the result. Since this
26 //! behavior is not enforceable by traits, `&&` and `||` are not supported as
27 //! overloadable operators.
29 //! Many of the operators take their operands by value. In non-generic
30 //! contexts involving built-in types, this is usually not a problem.
31 //! However, using these operators in generic code, requires some
32 //! attention if values have to be reused as opposed to letting the operators
33 //! consume them. One option is to occasionally use [`clone`].
34 //! Another option is to rely on the types involved providing additional
35 //! operator implementations for references. For example, for a user-defined
36 //! type `T` which is supposed to support addition, it is probably a good
37 //! idea to have both `T` and `&T` implement the traits [`Add<T>`][`Add`] and
38 //! [`Add<&T>`][`Add`] so that generic code can be written without unnecessary
43 //! This example creates a `Point` struct that implements [`Add`] and [`Sub`],
44 //! and then demonstrates adding and subtracting two `Point`s.
47 //! use std::ops::{Add, Sub};
55 //! impl Add for Point {
56 //! type Output = Point;
58 //! fn add(self, other: Point) -> Point {
59 //! Point {x: self.x + other.x, y: self.y + other.y}
63 //! impl Sub for Point {
64 //! type Output = Point;
66 //! fn sub(self, other: Point) -> Point {
67 //! Point {x: self.x - other.x, y: self.y - other.y}
71 //! println!("{:?}", Point {x: 1, y: 0} + Point {x: 2, y: 3});
72 //! println!("{:?}", Point {x: 1, y: 0} - Point {x: 2, y: 3});
76 //! See the documentation for each trait for an example implementation.
78 //! The [`Fn`], [`FnMut`], and [`FnOnce`] traits are implemented by types that can be
79 //! invoked like functions. Note that [`Fn`] takes `&self`, [`FnMut`] takes `&mut
80 //! self` and [`FnOnce`] takes `self`. These correspond to the three kinds of
81 //! methods that can be invoked on an instance: call-by-reference,
82 //! call-by-mutable-reference, and call-by-value. The most common use of these
83 //! traits is to act as bounds to higher-level functions that take functions or
84 //! closures as arguments.
86 //! Taking a [`Fn`] as a parameter:
89 //! fn call_with_one<F>(func: F) -> usize
90 //! where F: Fn(usize) -> usize
95 //! let double = |x| x * 2;
96 //! assert_eq!(call_with_one(double), 2);
99 //! Taking a [`FnMut`] as a parameter:
102 //! fn do_twice<F>(mut func: F)
109 //! let mut x: usize = 1;
111 //! let add_two_to_x = || x += 2;
112 //! do_twice(add_two_to_x);
115 //! assert_eq!(x, 5);
118 //! Taking a [`FnOnce`] as a parameter:
121 //! fn consume_with_relish<F>(func: F)
122 //! where F: FnOnce() -> String
124 //! // `func` consumes its captured variables, so it cannot be run more
126 //! println!("Consumed: {}", func());
128 //! println!("Delicious!");
130 //! // Attempting to invoke `func()` again will throw a `use of moved
131 //! // value` error for `func`
134 //! let x = String::from("x");
135 //! let consume_and_return_x = move || x;
136 //! consume_with_relish(consume_and_return_x);
138 //! // `consume_and_return_x` can no longer be invoked at this point
141 //! [`Fn`]: trait.Fn.html
142 //! [`FnMut`]: trait.FnMut.html
143 //! [`FnOnce`]: trait.FnOnce.html
144 //! [`Add`]: trait.Add.html
145 //! [`Sub`]: trait.Sub.html
146 //! [`clone`]: ../clone/trait.Clone.html#tymethod.clone
148 #![stable(feature = "rust1", since = "1.0.0")]
153 /// The `Drop` trait is used to run some code when a value goes out of scope.
154 /// This is sometimes called a 'destructor'.
158 /// A trivial implementation of `Drop`. The `drop` method is called when `_x`
159 /// goes out of scope, and therefore `main` prints `Dropping!`.
164 /// impl Drop for HasDrop {
165 /// fn drop(&mut self) {
166 /// println!("Dropping!");
171 /// let _x = HasDrop;
175 #[stable(feature = "rust1", since = "1.0.0")]
177 /// A method called when the value goes out of scope.
179 /// When this method has been called, `self` has not yet been deallocated.
180 /// If it were, `self` would be a dangling reference.
182 /// After this function is over, the memory of `self` will be deallocated.
184 /// This function cannot be called explicitly. This is compiler error
185 /// [E0040]. However, the [`std::mem::drop`] function in the prelude can be
186 /// used to call the argument's `Drop` implementation.
188 /// [E0040]: ../../error-index.html#E0040
189 /// [`std::mem::drop`]: ../../std/mem/fn.drop.html
193 /// Given that a `panic!` will call `drop()` as it unwinds, any `panic!` in
194 /// a `drop()` implementation will likely abort.
195 #[stable(feature = "rust1", since = "1.0.0")]
199 /// The addition operator `+`.
203 /// This example creates a `Point` struct that implements the `Add` trait, and
204 /// then demonstrates adding two `Point`s.
207 /// use std::ops::Add;
215 /// impl Add for Point {
216 /// type Output = Point;
218 /// fn add(self, other: Point) -> Point {
220 /// x: self.x + other.x,
221 /// y: self.y + other.y,
226 /// impl PartialEq for Point {
227 /// fn eq(&self, other: &Self) -> bool {
228 /// self.x == other.x && self.y == other.y
233 /// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
234 /// Point { x: 3, y: 3 });
238 /// Here is an example of the same `Point` struct implementing the `Add` trait
242 /// use std::ops::Add;
245 /// struct Point<T> {
250 /// // Notice that the implementation uses the `Output` associated type
251 /// impl<T: Add<Output=T>> Add for Point<T> {
252 /// type Output = Point<T>;
254 /// fn add(self, other: Point<T>) -> Point<T> {
256 /// x: self.x + other.x,
257 /// y: self.y + other.y,
262 /// impl<T: PartialEq> PartialEq for Point<T> {
263 /// fn eq(&self, other: &Self) -> bool {
264 /// self.x == other.x && self.y == other.y
269 /// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
270 /// Point { x: 3, y: 3 });
274 /// Note that `RHS = Self` by default, but this is not mandatory. For example,
275 /// [std::time::SystemTime] implements `Add<Duration>`, which permits
276 /// operations of the form `SystemTime = SystemTime + Duration`.
278 /// [std::time::SystemTime]: ../../std/time/struct.SystemTime.html
280 #[stable(feature = "rust1", since = "1.0.0")]
281 #[rustc_on_unimplemented = "no implementation for `{Self} + {RHS}`"]
282 pub trait Add<RHS=Self> {
283 /// The resulting type after applying the `+` operator
284 #[stable(feature = "rust1", since = "1.0.0")]
287 /// The method for the `+` operator
288 #[stable(feature = "rust1", since = "1.0.0")]
289 fn add(self, rhs: RHS) -> Self::Output;
292 macro_rules! add_impl {
294 #[stable(feature = "rust1", since = "1.0.0")]
299 #[rustc_inherit_overflow_checks]
300 fn add(self, other: $t) -> $t { self + other }
303 forward_ref_binop! { impl Add, add for $t, $t }
307 add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
309 /// The subtraction operator `-`.
313 /// This example creates a `Point` struct that implements the `Sub` trait, and
314 /// then demonstrates subtracting two `Point`s.
317 /// use std::ops::Sub;
325 /// impl Sub for Point {
326 /// type Output = Point;
328 /// fn sub(self, other: Point) -> Point {
330 /// x: self.x - other.x,
331 /// y: self.y - other.y,
336 /// impl PartialEq for Point {
337 /// fn eq(&self, other: &Self) -> bool {
338 /// self.x == other.x && self.y == other.y
343 /// assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 },
344 /// Point { x: 1, y: 0 });
348 /// Note that `RHS = Self` by default, but this is not mandatory. For example,
349 /// [std::time::SystemTime] implements `Sub<Duration>`, which permits
350 /// operations of the form `SystemTime = SystemTime - Duration`.
352 /// [std::time::SystemTime]: ../../std/time/struct.SystemTime.html
354 #[stable(feature = "rust1", since = "1.0.0")]
355 #[rustc_on_unimplemented = "no implementation for `{Self} - {RHS}`"]
356 pub trait Sub<RHS=Self> {
357 /// The resulting type after applying the `-` operator
358 #[stable(feature = "rust1", since = "1.0.0")]
361 /// The method for the `-` operator
362 #[stable(feature = "rust1", since = "1.0.0")]
363 fn sub(self, rhs: RHS) -> Self::Output;
366 macro_rules! sub_impl {
368 #[stable(feature = "rust1", since = "1.0.0")]
373 #[rustc_inherit_overflow_checks]
374 fn sub(self, other: $t) -> $t { self - other }
377 forward_ref_binop! { impl Sub, sub for $t, $t }
381 sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
383 /// The multiplication operator `*`.
387 /// Implementing a `Mul`tipliable rational number struct:
390 /// use std::ops::Mul;
392 /// // The uniqueness of rational numbers in lowest terms is a consequence of
393 /// // the fundamental theorem of arithmetic.
395 /// #[derive(PartialEq, Debug)]
396 /// struct Rational {
397 /// nominator: usize,
398 /// denominator: usize,
402 /// fn new(nominator: usize, denominator: usize) -> Self {
403 /// if denominator == 0 {
404 /// panic!("Zero is an invalid denominator!");
407 /// // Reduce to lowest terms by dividing by the greatest common
409 /// let gcd = gcd(nominator, denominator);
411 /// nominator: nominator / gcd,
412 /// denominator: denominator / gcd,
417 /// impl Mul for Rational {
418 /// // The multiplication of rational numbers is a closed operation.
419 /// type Output = Self;
421 /// fn mul(self, rhs: Self) -> Self {
422 /// let nominator = self.nominator * rhs.nominator;
423 /// let denominator = self.denominator * rhs.denominator;
424 /// Rational::new(nominator, denominator)
428 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
430 /// fn gcd(x: usize, y: usize) -> usize {
441 /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
442 /// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4),
443 /// Rational::new(1, 2));
446 /// Note that `RHS = Self` by default, but this is not mandatory. Here is an
447 /// implementation which enables multiplication of vectors by scalars, as is
448 /// done in linear algebra.
451 /// use std::ops::Mul;
453 /// struct Scalar {value: usize};
456 /// struct Vector {value: Vec<usize>};
458 /// impl Mul<Vector> for Scalar {
459 /// type Output = Vector;
461 /// fn mul(self, rhs: Vector) -> Vector {
462 /// Vector {value: rhs.value.iter().map(|v| self.value * v).collect()}
466 /// impl PartialEq<Vector> for Vector {
467 /// fn eq(&self, other: &Self) -> bool {
468 /// self.value == other.value
472 /// let scalar = Scalar{value: 3};
473 /// let vector = Vector{value: vec![2, 4, 6]};
474 /// assert_eq!(scalar * vector, Vector{value: vec![6, 12, 18]});
477 #[stable(feature = "rust1", since = "1.0.0")]
478 #[rustc_on_unimplemented = "no implementation for `{Self} * {RHS}`"]
479 pub trait Mul<RHS=Self> {
480 /// The resulting type after applying the `*` operator
481 #[stable(feature = "rust1", since = "1.0.0")]
484 /// The method for the `*` operator
485 #[stable(feature = "rust1", since = "1.0.0")]
486 fn mul(self, rhs: RHS) -> Self::Output;
489 macro_rules! mul_impl {
491 #[stable(feature = "rust1", since = "1.0.0")]
496 #[rustc_inherit_overflow_checks]
497 fn mul(self, other: $t) -> $t { self * other }
500 forward_ref_binop! { impl Mul, mul for $t, $t }
504 mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
506 /// The division operator `/`.
510 /// Implementing a `Div`idable rational number struct:
513 /// use std::ops::Div;
515 /// // The uniqueness of rational numbers in lowest terms is a consequence of
516 /// // the fundamental theorem of arithmetic.
518 /// #[derive(PartialEq, Debug)]
519 /// struct Rational {
520 /// nominator: usize,
521 /// denominator: usize,
525 /// fn new(nominator: usize, denominator: usize) -> Self {
526 /// if denominator == 0 {
527 /// panic!("Zero is an invalid denominator!");
530 /// // Reduce to lowest terms by dividing by the greatest common
532 /// let gcd = gcd(nominator, denominator);
534 /// nominator: nominator / gcd,
535 /// denominator: denominator / gcd,
540 /// impl Div for Rational {
541 /// // The division of rational numbers is a closed operation.
542 /// type Output = Self;
544 /// fn div(self, rhs: Self) -> Self {
545 /// if rhs.nominator == 0 {
546 /// panic!("Cannot divide by zero-valued `Rational`!");
549 /// let nominator = self.nominator * rhs.denominator;
550 /// let denominator = self.denominator * rhs.nominator;
551 /// Rational::new(nominator, denominator)
555 /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
557 /// fn gcd(x: usize, y: usize) -> usize {
569 /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
570 /// assert_eq!(Rational::new(1, 2) / Rational::new(3, 4),
571 /// Rational::new(2, 3));
575 /// Note that `RHS = Self` by default, but this is not mandatory. Here is an
576 /// implementation which enables division of vectors by scalars, as is done in
580 /// use std::ops::Div;
582 /// struct Scalar {value: f32};
585 /// struct Vector {value: Vec<f32>};
587 /// impl Div<Scalar> for Vector {
588 /// type Output = Vector;
590 /// fn div(self, rhs: Scalar) -> Vector {
591 /// Vector {value: self.value.iter().map(|v| v / rhs.value).collect()}
595 /// impl PartialEq<Vector> for Vector {
596 /// fn eq(&self, other: &Self) -> bool {
597 /// self.value == other.value
601 /// let scalar = Scalar{value: 2f32};
602 /// let vector = Vector{value: vec![2f32, 4f32, 6f32]};
603 /// assert_eq!(vector / scalar, Vector{value: vec![1f32, 2f32, 3f32]});
606 #[stable(feature = "rust1", since = "1.0.0")]
607 #[rustc_on_unimplemented = "no implementation for `{Self} / {RHS}`"]
608 pub trait Div<RHS=Self> {
609 /// The resulting type after applying the `/` operator
610 #[stable(feature = "rust1", since = "1.0.0")]
613 /// The method for the `/` operator
614 #[stable(feature = "rust1", since = "1.0.0")]
615 fn div(self, rhs: RHS) -> Self::Output;
618 macro_rules! div_impl_integer {
620 /// This operation rounds towards zero, truncating any
621 /// fractional part of the exact result.
622 #[stable(feature = "rust1", since = "1.0.0")]
627 fn div(self, other: $t) -> $t { self / other }
630 forward_ref_binop! { impl Div, div for $t, $t }
634 div_impl_integer! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
636 macro_rules! div_impl_float {
638 #[stable(feature = "rust1", since = "1.0.0")]
643 fn div(self, other: $t) -> $t { self / other }
646 forward_ref_binop! { impl Div, div for $t, $t }
650 div_impl_float! { f32 f64 }
652 /// The remainder operator `%`.
656 /// This example implements `Rem` on a `SplitSlice` object. After `Rem` is
657 /// implemented, one can use the `%` operator to find out what the remaining
658 /// elements of the slice would be after splitting it into equal slices of a
662 /// use std::ops::Rem;
664 /// #[derive(PartialEq, Debug)]
665 /// struct SplitSlice<'a, T: 'a> {
669 /// impl<'a, T> Rem<usize> for SplitSlice<'a, T> {
670 /// type Output = SplitSlice<'a, T>;
672 /// fn rem(self, modulus: usize) -> Self {
673 /// let len = self.slice.len();
674 /// let rem = len % modulus;
675 /// let start = len - rem;
676 /// SplitSlice {slice: &self.slice[start..]}
680 /// // If we were to divide &[0, 1, 2, 3, 4, 5, 6, 7] into slices of size 3,
681 /// // the remainder would be &[6, 7]
682 /// assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3,
683 /// SplitSlice { slice: &[6, 7] });
686 #[stable(feature = "rust1", since = "1.0.0")]
687 #[rustc_on_unimplemented = "no implementation for `{Self} % {RHS}`"]
688 pub trait Rem<RHS=Self> {
689 /// The resulting type after applying the `%` operator
690 #[stable(feature = "rust1", since = "1.0.0")]
693 /// The method for the `%` operator
694 #[stable(feature = "rust1", since = "1.0.0")]
695 fn rem(self, rhs: RHS) -> Self::Output;
698 macro_rules! rem_impl_integer {
700 /// This operation satisfies `n % d == n - (n / d) * d`. The
701 /// result has the same sign as the left operand.
702 #[stable(feature = "rust1", since = "1.0.0")]
707 fn rem(self, other: $t) -> $t { self % other }
710 forward_ref_binop! { impl Rem, rem for $t, $t }
714 rem_impl_integer! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
717 macro_rules! rem_impl_float {
719 #[stable(feature = "rust1", since = "1.0.0")]
724 fn rem(self, other: $t) -> $t { self % other }
727 forward_ref_binop! { impl Rem, rem for $t, $t }
731 rem_impl_float! { f32 f64 }
733 /// The unary negation operator `-`.
737 /// An implementation of `Neg` for `Sign`, which allows the use of `-` to
738 /// negate its value.
741 /// use std::ops::Neg;
743 /// #[derive(Debug, PartialEq)]
750 /// impl Neg for Sign {
751 /// type Output = Sign;
753 /// fn neg(self) -> Sign {
755 /// Sign::Negative => Sign::Positive,
756 /// Sign::Zero => Sign::Zero,
757 /// Sign::Positive => Sign::Negative,
762 /// // a negative positive is a negative
763 /// assert_eq!(-Sign::Positive, Sign::Negative);
764 /// // a double negative is a positive
765 /// assert_eq!(-Sign::Negative, Sign::Positive);
766 /// // zero is its own negation
767 /// assert_eq!(-Sign::Zero, Sign::Zero);
770 #[stable(feature = "rust1", since = "1.0.0")]
772 /// The resulting type after applying the `-` operator
773 #[stable(feature = "rust1", since = "1.0.0")]
776 /// The method for the unary `-` operator
777 #[stable(feature = "rust1", since = "1.0.0")]
778 fn neg(self) -> Self::Output;
783 macro_rules! neg_impl_core {
784 ($id:ident => $body:expr, $($t:ty)*) => ($(
785 #[stable(feature = "rust1", since = "1.0.0")]
790 #[rustc_inherit_overflow_checks]
791 fn neg(self) -> $t { let $id = self; $body }
794 forward_ref_unop! { impl Neg, neg for $t }
798 macro_rules! neg_impl_numeric {
799 ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} }
802 #[allow(unused_macros)]
803 macro_rules! neg_impl_unsigned {
805 neg_impl_core!{ x => {
810 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
811 neg_impl_numeric! { isize i8 i16 i32 i64 i128 f32 f64 }
813 /// The unary logical negation operator `!`.
817 /// An implementation of `Not` for `Answer`, which enables the use of `!` to
818 /// invert its value.
821 /// use std::ops::Not;
823 /// #[derive(Debug, PartialEq)]
829 /// impl Not for Answer {
830 /// type Output = Answer;
832 /// fn not(self) -> Answer {
834 /// Answer::Yes => Answer::No,
835 /// Answer::No => Answer::Yes
840 /// assert_eq!(!Answer::Yes, Answer::No);
841 /// assert_eq!(!Answer::No, Answer::Yes);
844 #[stable(feature = "rust1", since = "1.0.0")]
846 /// The resulting type after applying the `!` operator
847 #[stable(feature = "rust1", since = "1.0.0")]
850 /// The method for the unary `!` operator
851 #[stable(feature = "rust1", since = "1.0.0")]
852 fn not(self) -> Self::Output;
855 macro_rules! not_impl {
857 #[stable(feature = "rust1", since = "1.0.0")]
862 fn not(self) -> $t { !self }
865 forward_ref_unop! { impl Not, not for $t }
869 not_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
871 /// The bitwise AND operator `&`.
875 /// In this example, the `&` operator is lifted to a trivial `Scalar` type.
878 /// use std::ops::BitAnd;
880 /// #[derive(Debug, PartialEq)]
881 /// struct Scalar(bool);
883 /// impl BitAnd for Scalar {
884 /// type Output = Self;
886 /// // rhs is the "right-hand side" of the expression `a & b`
887 /// fn bitand(self, rhs: Self) -> Self {
888 /// Scalar(self.0 & rhs.0)
893 /// assert_eq!(Scalar(true) & Scalar(true), Scalar(true));
894 /// assert_eq!(Scalar(true) & Scalar(false), Scalar(false));
895 /// assert_eq!(Scalar(false) & Scalar(true), Scalar(false));
896 /// assert_eq!(Scalar(false) & Scalar(false), Scalar(false));
900 /// In this example, the `BitAnd` trait is implemented for a `BooleanVector`
904 /// use std::ops::BitAnd;
906 /// #[derive(Debug, PartialEq)]
907 /// struct BooleanVector(Vec<bool>);
909 /// impl BitAnd for BooleanVector {
910 /// type Output = Self;
912 /// fn bitand(self, BooleanVector(rhs): Self) -> Self {
913 /// let BooleanVector(lhs) = self;
914 /// assert_eq!(lhs.len(), rhs.len());
915 /// BooleanVector(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x && *y).collect())
920 /// let bv1 = BooleanVector(vec![true, true, false, false]);
921 /// let bv2 = BooleanVector(vec![true, false, true, false]);
922 /// let expected = BooleanVector(vec![true, false, false, false]);
923 /// assert_eq!(bv1 & bv2, expected);
927 #[stable(feature = "rust1", since = "1.0.0")]
928 #[rustc_on_unimplemented = "no implementation for `{Self} & {RHS}`"]
929 pub trait BitAnd<RHS=Self> {
930 /// The resulting type after applying the `&` operator
931 #[stable(feature = "rust1", since = "1.0.0")]
934 /// The method for the `&` operator
935 #[stable(feature = "rust1", since = "1.0.0")]
936 fn bitand(self, rhs: RHS) -> Self::Output;
939 macro_rules! bitand_impl {
941 #[stable(feature = "rust1", since = "1.0.0")]
946 fn bitand(self, rhs: $t) -> $t { self & rhs }
949 forward_ref_binop! { impl BitAnd, bitand for $t, $t }
953 bitand_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
955 /// The bitwise OR operator `|`.
959 /// In this example, the `|` operator is lifted to a trivial `Scalar` type.
962 /// use std::ops::BitOr;
964 /// #[derive(Debug, PartialEq)]
965 /// struct Scalar(bool);
967 /// impl BitOr for Scalar {
968 /// type Output = Self;
970 /// // rhs is the "right-hand side" of the expression `a | b`
971 /// fn bitor(self, rhs: Self) -> Self {
972 /// Scalar(self.0 | rhs.0)
977 /// assert_eq!(Scalar(true) | Scalar(true), Scalar(true));
978 /// assert_eq!(Scalar(true) | Scalar(false), Scalar(true));
979 /// assert_eq!(Scalar(false) | Scalar(true), Scalar(true));
980 /// assert_eq!(Scalar(false) | Scalar(false), Scalar(false));
984 /// In this example, the `BitOr` trait is implemented for a `BooleanVector`
988 /// use std::ops::BitOr;
990 /// #[derive(Debug, PartialEq)]
991 /// struct BooleanVector(Vec<bool>);
993 /// impl BitOr for BooleanVector {
994 /// type Output = Self;
996 /// fn bitor(self, BooleanVector(rhs): Self) -> Self {
997 /// let BooleanVector(lhs) = self;
998 /// assert_eq!(lhs.len(), rhs.len());
999 /// BooleanVector(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x || *y).collect())
1004 /// let bv1 = BooleanVector(vec![true, true, false, false]);
1005 /// let bv2 = BooleanVector(vec![true, false, true, false]);
1006 /// let expected = BooleanVector(vec![true, true, true, false]);
1007 /// assert_eq!(bv1 | bv2, expected);
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 #[rustc_on_unimplemented = "no implementation for `{Self} | {RHS}`"]
1013 pub trait BitOr<RHS=Self> {
1014 /// The resulting type after applying the `|` operator
1015 #[stable(feature = "rust1", since = "1.0.0")]
1018 /// The method for the `|` operator
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 fn bitor(self, rhs: RHS) -> Self::Output;
1023 macro_rules! bitor_impl {
1025 #[stable(feature = "rust1", since = "1.0.0")]
1030 fn bitor(self, rhs: $t) -> $t { self | rhs }
1033 forward_ref_binop! { impl BitOr, bitor for $t, $t }
1037 bitor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1039 /// The bitwise XOR operator `^`.
1043 /// In this example, the `^` operator is lifted to a trivial `Scalar` type.
1046 /// use std::ops::BitXor;
1048 /// #[derive(Debug, PartialEq)]
1049 /// struct Scalar(bool);
1051 /// impl BitXor for Scalar {
1052 /// type Output = Self;
1054 /// // rhs is the "right-hand side" of the expression `a ^ b`
1055 /// fn bitxor(self, rhs: Self) -> Self {
1056 /// Scalar(self.0 ^ rhs.0)
1061 /// assert_eq!(Scalar(true) ^ Scalar(true), Scalar(false));
1062 /// assert_eq!(Scalar(true) ^ Scalar(false), Scalar(true));
1063 /// assert_eq!(Scalar(false) ^ Scalar(true), Scalar(true));
1064 /// assert_eq!(Scalar(false) ^ Scalar(false), Scalar(false));
1068 /// In this example, the `BitXor` trait is implemented for a `BooleanVector`
1072 /// use std::ops::BitXor;
1074 /// #[derive(Debug, PartialEq)]
1075 /// struct BooleanVector(Vec<bool>);
1077 /// impl BitXor for BooleanVector {
1078 /// type Output = Self;
1080 /// fn bitxor(self, BooleanVector(rhs): Self) -> Self {
1081 /// let BooleanVector(lhs) = self;
1082 /// assert_eq!(lhs.len(), rhs.len());
1083 /// BooleanVector(lhs.iter()
1084 /// .zip(rhs.iter())
1085 /// .map(|(x, y)| (*x || *y) && !(*x && *y))
1091 /// let bv1 = BooleanVector(vec![true, true, false, false]);
1092 /// let bv2 = BooleanVector(vec![true, false, true, false]);
1093 /// let expected = BooleanVector(vec![false, true, true, false]);
1094 /// assert_eq!(bv1 ^ bv2, expected);
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 #[rustc_on_unimplemented = "no implementation for `{Self} ^ {RHS}`"]
1100 pub trait BitXor<RHS=Self> {
1101 /// The resulting type after applying the `^` operator
1102 #[stable(feature = "rust1", since = "1.0.0")]
1105 /// The method for the `^` operator
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 fn bitxor(self, rhs: RHS) -> Self::Output;
1110 macro_rules! bitxor_impl {
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 impl BitXor for $t {
1117 fn bitxor(self, other: $t) -> $t { self ^ other }
1120 forward_ref_binop! { impl BitXor, bitxor for $t, $t }
1124 bitxor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1126 /// The left shift operator `<<`.
1130 /// An implementation of `Shl` that lifts the `<<` operation on integers to a
1131 /// `Scalar` struct.
1134 /// use std::ops::Shl;
1136 /// #[derive(PartialEq, Debug)]
1137 /// struct Scalar(usize);
1139 /// impl Shl<Scalar> for Scalar {
1140 /// type Output = Self;
1142 /// fn shl(self, Scalar(rhs): Self) -> Scalar {
1143 /// let Scalar(lhs) = self;
1144 /// Scalar(lhs << rhs)
1148 /// assert_eq!(Scalar(4) << Scalar(2), Scalar(16));
1152 /// An implementation of `Shl` that spins a vector leftward by a given amount.
1155 /// use std::ops::Shl;
1157 /// #[derive(PartialEq, Debug)]
1158 /// struct SpinVector<T: Clone> {
1162 /// impl<T: Clone> Shl<usize> for SpinVector<T> {
1163 /// type Output = Self;
1165 /// fn shl(self, rhs: usize) -> SpinVector<T> {
1166 /// // rotate the vector by `rhs` places
1167 /// let (a, b) = self.vec.split_at(rhs);
1168 /// let mut spun_vector: Vec<T> = vec![];
1169 /// spun_vector.extend_from_slice(b);
1170 /// spun_vector.extend_from_slice(a);
1171 /// SpinVector { vec: spun_vector }
1176 /// assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } << 2,
1177 /// SpinVector { vec: vec![2, 3, 4, 0, 1] });
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 #[rustc_on_unimplemented = "no implementation for `{Self} << {RHS}`"]
1183 pub trait Shl<RHS> {
1184 /// The resulting type after applying the `<<` operator
1185 #[stable(feature = "rust1", since = "1.0.0")]
1188 /// The method for the `<<` operator
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 fn shl(self, rhs: RHS) -> Self::Output;
1193 macro_rules! shl_impl {
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 impl Shl<$f> for $t {
1200 #[rustc_inherit_overflow_checks]
1201 fn shl(self, other: $f) -> $t {
1206 forward_ref_binop! { impl Shl, shl for $t, $f }
1210 macro_rules! shl_impl_all {
1212 shl_impl! { $t, u8 }
1213 shl_impl! { $t, u16 }
1214 shl_impl! { $t, u32 }
1215 shl_impl! { $t, u64 }
1216 shl_impl! { $t, u128 }
1217 shl_impl! { $t, usize }
1219 shl_impl! { $t, i8 }
1220 shl_impl! { $t, i16 }
1221 shl_impl! { $t, i32 }
1222 shl_impl! { $t, i64 }
1223 shl_impl! { $t, i128 }
1224 shl_impl! { $t, isize }
1228 shl_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 isize i128 }
1230 /// The right shift operator `>>`.
1234 /// An implementation of `Shr` that lifts the `>>` operation on integers to a
1235 /// `Scalar` struct.
1238 /// use std::ops::Shr;
1240 /// #[derive(PartialEq, Debug)]
1241 /// struct Scalar(usize);
1243 /// impl Shr<Scalar> for Scalar {
1244 /// type Output = Self;
1246 /// fn shr(self, Scalar(rhs): Self) -> Scalar {
1247 /// let Scalar(lhs) = self;
1248 /// Scalar(lhs >> rhs)
1252 /// assert_eq!(Scalar(16) >> Scalar(2), Scalar(4));
1256 /// An implementation of `Shr` that spins a vector rightward by a given amount.
1259 /// use std::ops::Shr;
1261 /// #[derive(PartialEq, Debug)]
1262 /// struct SpinVector<T: Clone> {
1266 /// impl<T: Clone> Shr<usize> for SpinVector<T> {
1267 /// type Output = Self;
1269 /// fn shr(self, rhs: usize) -> SpinVector<T> {
1270 /// // rotate the vector by `rhs` places
1271 /// let (a, b) = self.vec.split_at(self.vec.len() - rhs);
1272 /// let mut spun_vector: Vec<T> = vec![];
1273 /// spun_vector.extend_from_slice(b);
1274 /// spun_vector.extend_from_slice(a);
1275 /// SpinVector { vec: spun_vector }
1280 /// assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } >> 2,
1281 /// SpinVector { vec: vec![3, 4, 0, 1, 2] });
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 #[rustc_on_unimplemented = "no implementation for `{Self} >> {RHS}`"]
1287 pub trait Shr<RHS> {
1288 /// The resulting type after applying the `>>` operator
1289 #[stable(feature = "rust1", since = "1.0.0")]
1292 /// The method for the `>>` operator
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 fn shr(self, rhs: RHS) -> Self::Output;
1297 macro_rules! shr_impl {
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl Shr<$f> for $t {
1304 #[rustc_inherit_overflow_checks]
1305 fn shr(self, other: $f) -> $t {
1310 forward_ref_binop! { impl Shr, shr for $t, $f }
1314 macro_rules! shr_impl_all {
1316 shr_impl! { $t, u8 }
1317 shr_impl! { $t, u16 }
1318 shr_impl! { $t, u32 }
1319 shr_impl! { $t, u64 }
1320 shr_impl! { $t, u128 }
1321 shr_impl! { $t, usize }
1323 shr_impl! { $t, i8 }
1324 shr_impl! { $t, i16 }
1325 shr_impl! { $t, i32 }
1326 shr_impl! { $t, i64 }
1327 shr_impl! { $t, i128 }
1328 shr_impl! { $t, isize }
1332 shr_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1334 /// The addition assignment operator `+=`.
1338 /// This example creates a `Point` struct that implements the `AddAssign`
1339 /// trait, and then demonstrates add-assigning to a mutable `Point`.
1342 /// use std::ops::AddAssign;
1344 /// #[derive(Debug)]
1350 /// impl AddAssign for Point {
1351 /// fn add_assign(&mut self, other: Point) {
1353 /// x: self.x + other.x,
1354 /// y: self.y + other.y,
1359 /// impl PartialEq for Point {
1360 /// fn eq(&self, other: &Self) -> bool {
1361 /// self.x == other.x && self.y == other.y
1365 /// let mut point = Point { x: 1, y: 0 };
1366 /// point += Point { x: 2, y: 3 };
1367 /// assert_eq!(point, Point { x: 3, y: 3 });
1369 #[lang = "add_assign"]
1370 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1371 #[rustc_on_unimplemented = "no implementation for `{Self} += {Rhs}`"]
1372 pub trait AddAssign<Rhs=Self> {
1373 /// The method for the `+=` operator
1374 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1375 fn add_assign(&mut self, rhs: Rhs);
1378 macro_rules! add_assign_impl {
1380 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1381 impl AddAssign for $t {
1383 #[rustc_inherit_overflow_checks]
1384 fn add_assign(&mut self, other: $t) { *self += other }
1389 add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1391 /// The subtraction assignment operator `-=`.
1395 /// This example creates a `Point` struct that implements the `SubAssign`
1396 /// trait, and then demonstrates sub-assigning to a mutable `Point`.
1399 /// use std::ops::SubAssign;
1401 /// #[derive(Debug)]
1407 /// impl SubAssign for Point {
1408 /// fn sub_assign(&mut self, other: Point) {
1410 /// x: self.x - other.x,
1411 /// y: self.y - other.y,
1416 /// impl PartialEq for Point {
1417 /// fn eq(&self, other: &Self) -> bool {
1418 /// self.x == other.x && self.y == other.y
1422 /// let mut point = Point { x: 3, y: 3 };
1423 /// point -= Point { x: 2, y: 3 };
1424 /// assert_eq!(point, Point {x: 1, y: 0});
1426 #[lang = "sub_assign"]
1427 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1428 #[rustc_on_unimplemented = "no implementation for `{Self} -= {Rhs}`"]
1429 pub trait SubAssign<Rhs=Self> {
1430 /// The method for the `-=` operator
1431 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1432 fn sub_assign(&mut self, rhs: Rhs);
1435 macro_rules! sub_assign_impl {
1437 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1438 impl SubAssign for $t {
1440 #[rustc_inherit_overflow_checks]
1441 fn sub_assign(&mut self, other: $t) { *self -= other }
1446 sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1448 /// The multiplication assignment operator `*=`.
1452 /// A trivial implementation of `MulAssign`. When `Foo *= Foo` happens, it ends up
1453 /// calling `mul_assign`, and therefore, `main` prints `Multiplying!`.
1456 /// use std::ops::MulAssign;
1460 /// impl MulAssign for Foo {
1461 /// fn mul_assign(&mut self, _rhs: Foo) {
1462 /// println!("Multiplying!");
1466 /// # #[allow(unused_assignments)]
1468 /// let mut foo = Foo;
1472 #[lang = "mul_assign"]
1473 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1474 #[rustc_on_unimplemented = "no implementation for `{Self} *= {Rhs}`"]
1475 pub trait MulAssign<Rhs=Self> {
1476 /// The method for the `*=` operator
1477 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1478 fn mul_assign(&mut self, rhs: Rhs);
1481 macro_rules! mul_assign_impl {
1483 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1484 impl MulAssign for $t {
1486 #[rustc_inherit_overflow_checks]
1487 fn mul_assign(&mut self, other: $t) { *self *= other }
1492 mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1494 /// The division assignment operator `/=`.
1498 /// A trivial implementation of `DivAssign`. When `Foo /= Foo` happens, it ends up
1499 /// calling `div_assign`, and therefore, `main` prints `Dividing!`.
1502 /// use std::ops::DivAssign;
1506 /// impl DivAssign for Foo {
1507 /// fn div_assign(&mut self, _rhs: Foo) {
1508 /// println!("Dividing!");
1512 /// # #[allow(unused_assignments)]
1514 /// let mut foo = Foo;
1518 #[lang = "div_assign"]
1519 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1520 #[rustc_on_unimplemented = "no implementation for `{Self} /= {Rhs}`"]
1521 pub trait DivAssign<Rhs=Self> {
1522 /// The method for the `/=` operator
1523 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1524 fn div_assign(&mut self, rhs: Rhs);
1527 macro_rules! div_assign_impl {
1529 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1530 impl DivAssign for $t {
1532 fn div_assign(&mut self, other: $t) { *self /= other }
1537 div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1539 /// The remainder assignment operator `%=`.
1543 /// A trivial implementation of `RemAssign`. When `Foo %= Foo` happens, it ends up
1544 /// calling `rem_assign`, and therefore, `main` prints `Remainder-ing!`.
1547 /// use std::ops::RemAssign;
1551 /// impl RemAssign for Foo {
1552 /// fn rem_assign(&mut self, _rhs: Foo) {
1553 /// println!("Remainder-ing!");
1557 /// # #[allow(unused_assignments)]
1559 /// let mut foo = Foo;
1563 #[lang = "rem_assign"]
1564 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1565 #[rustc_on_unimplemented = "no implementation for `{Self} %= {Rhs}`"]
1566 pub trait RemAssign<Rhs=Self> {
1567 /// The method for the `%=` operator
1568 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1569 fn rem_assign(&mut self, rhs: Rhs);
1572 macro_rules! rem_assign_impl {
1574 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1575 impl RemAssign for $t {
1577 fn rem_assign(&mut self, other: $t) { *self %= other }
1582 rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1584 /// The bitwise AND assignment operator `&=`.
1588 /// In this example, the `&=` operator is lifted to a trivial `Scalar` type.
1591 /// use std::ops::BitAndAssign;
1593 /// #[derive(Debug, PartialEq)]
1594 /// struct Scalar(bool);
1596 /// impl BitAndAssign for Scalar {
1597 /// // rhs is the "right-hand side" of the expression `a &= b`
1598 /// fn bitand_assign(&mut self, rhs: Self) {
1599 /// *self = Scalar(self.0 & rhs.0)
1604 /// let mut scalar = Scalar(true);
1605 /// scalar &= Scalar(true);
1606 /// assert_eq!(scalar, Scalar(true));
1608 /// let mut scalar = Scalar(true);
1609 /// scalar &= Scalar(false);
1610 /// assert_eq!(scalar, Scalar(false));
1612 /// let mut scalar = Scalar(false);
1613 /// scalar &= Scalar(true);
1614 /// assert_eq!(scalar, Scalar(false));
1616 /// let mut scalar = Scalar(false);
1617 /// scalar &= Scalar(false);
1618 /// assert_eq!(scalar, Scalar(false));
1622 /// In this example, the `BitAndAssign` trait is implemented for a
1623 /// `BooleanVector` struct.
1626 /// use std::ops::BitAndAssign;
1628 /// #[derive(Debug, PartialEq)]
1629 /// struct BooleanVector(Vec<bool>);
1631 /// impl BitAndAssign for BooleanVector {
1632 /// // rhs is the "right-hand side" of the expression `a &= b`
1633 /// fn bitand_assign(&mut self, rhs: Self) {
1634 /// assert_eq!(self.0.len(), rhs.0.len());
1635 /// *self = BooleanVector(self.0
1637 /// .zip(rhs.0.iter())
1638 /// .map(|(x, y)| *x && *y)
1644 /// let mut bv = BooleanVector(vec![true, true, false, false]);
1645 /// bv &= BooleanVector(vec![true, false, true, false]);
1646 /// let expected = BooleanVector(vec![true, false, false, false]);
1647 /// assert_eq!(bv, expected);
1650 #[lang = "bitand_assign"]
1651 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1652 #[rustc_on_unimplemented = "no implementation for `{Self} &= {Rhs}`"]
1653 pub trait BitAndAssign<Rhs=Self> {
1654 /// The method for the `&=` operator
1655 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1656 fn bitand_assign(&mut self, rhs: Rhs);
1659 macro_rules! bitand_assign_impl {
1661 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1662 impl BitAndAssign for $t {
1664 fn bitand_assign(&mut self, other: $t) { *self &= other }
1669 bitand_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1671 /// The bitwise OR assignment operator `|=`.
1675 /// A trivial implementation of `BitOrAssign`. When `Foo |= Foo` happens, it ends up
1676 /// calling `bitor_assign`, and therefore, `main` prints `Bitwise Or-ing!`.
1679 /// use std::ops::BitOrAssign;
1683 /// impl BitOrAssign for Foo {
1684 /// fn bitor_assign(&mut self, _rhs: Foo) {
1685 /// println!("Bitwise Or-ing!");
1689 /// # #[allow(unused_assignments)]
1691 /// let mut foo = Foo;
1695 #[lang = "bitor_assign"]
1696 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1697 #[rustc_on_unimplemented = "no implementation for `{Self} |= {Rhs}`"]
1698 pub trait BitOrAssign<Rhs=Self> {
1699 /// The method for the `|=` operator
1700 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1701 fn bitor_assign(&mut self, rhs: Rhs);
1704 macro_rules! bitor_assign_impl {
1706 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1707 impl BitOrAssign for $t {
1709 fn bitor_assign(&mut self, other: $t) { *self |= other }
1714 bitor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1716 /// The bitwise XOR assignment operator `^=`.
1720 /// A trivial implementation of `BitXorAssign`. When `Foo ^= Foo` happens, it ends up
1721 /// calling `bitxor_assign`, and therefore, `main` prints `Bitwise Xor-ing!`.
1724 /// use std::ops::BitXorAssign;
1728 /// impl BitXorAssign for Foo {
1729 /// fn bitxor_assign(&mut self, _rhs: Foo) {
1730 /// println!("Bitwise Xor-ing!");
1734 /// # #[allow(unused_assignments)]
1736 /// let mut foo = Foo;
1740 #[lang = "bitxor_assign"]
1741 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1742 #[rustc_on_unimplemented = "no implementation for `{Self} ^= {Rhs}`"]
1743 pub trait BitXorAssign<Rhs=Self> {
1744 /// The method for the `^=` operator
1745 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1746 fn bitxor_assign(&mut self, rhs: Rhs);
1749 macro_rules! bitxor_assign_impl {
1751 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1752 impl BitXorAssign for $t {
1754 fn bitxor_assign(&mut self, other: $t) { *self ^= other }
1759 bitxor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1761 /// The left shift assignment operator `<<=`.
1765 /// A trivial implementation of `ShlAssign`. When `Foo <<= Foo` happens, it ends up
1766 /// calling `shl_assign`, and therefore, `main` prints `Shifting left!`.
1769 /// use std::ops::ShlAssign;
1773 /// impl ShlAssign<Foo> for Foo {
1774 /// fn shl_assign(&mut self, _rhs: Foo) {
1775 /// println!("Shifting left!");
1779 /// # #[allow(unused_assignments)]
1781 /// let mut foo = Foo;
1785 #[lang = "shl_assign"]
1786 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1787 #[rustc_on_unimplemented = "no implementation for `{Self} <<= {Rhs}`"]
1788 pub trait ShlAssign<Rhs> {
1789 /// The method for the `<<=` operator
1790 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1791 fn shl_assign(&mut self, rhs: Rhs);
1794 macro_rules! shl_assign_impl {
1796 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1797 impl ShlAssign<$f> for $t {
1799 #[rustc_inherit_overflow_checks]
1800 fn shl_assign(&mut self, other: $f) {
1807 macro_rules! shl_assign_impl_all {
1809 shl_assign_impl! { $t, u8 }
1810 shl_assign_impl! { $t, u16 }
1811 shl_assign_impl! { $t, u32 }
1812 shl_assign_impl! { $t, u64 }
1813 shl_assign_impl! { $t, u128 }
1814 shl_assign_impl! { $t, usize }
1816 shl_assign_impl! { $t, i8 }
1817 shl_assign_impl! { $t, i16 }
1818 shl_assign_impl! { $t, i32 }
1819 shl_assign_impl! { $t, i64 }
1820 shl_assign_impl! { $t, i128 }
1821 shl_assign_impl! { $t, isize }
1825 shl_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1827 /// The right shift assignment operator `>>=`.
1831 /// A trivial implementation of `ShrAssign`. When `Foo >>= Foo` happens, it ends up
1832 /// calling `shr_assign`, and therefore, `main` prints `Shifting right!`.
1835 /// use std::ops::ShrAssign;
1839 /// impl ShrAssign<Foo> for Foo {
1840 /// fn shr_assign(&mut self, _rhs: Foo) {
1841 /// println!("Shifting right!");
1845 /// # #[allow(unused_assignments)]
1847 /// let mut foo = Foo;
1851 #[lang = "shr_assign"]
1852 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1853 #[rustc_on_unimplemented = "no implementation for `{Self} >>= {Rhs}`"]
1854 pub trait ShrAssign<Rhs=Self> {
1855 /// The method for the `>>=` operator
1856 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1857 fn shr_assign(&mut self, rhs: Rhs);
1860 macro_rules! shr_assign_impl {
1862 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1863 impl ShrAssign<$f> for $t {
1865 #[rustc_inherit_overflow_checks]
1866 fn shr_assign(&mut self, other: $f) {
1873 macro_rules! shr_assign_impl_all {
1875 shr_assign_impl! { $t, u8 }
1876 shr_assign_impl! { $t, u16 }
1877 shr_assign_impl! { $t, u32 }
1878 shr_assign_impl! { $t, u64 }
1879 shr_assign_impl! { $t, u128 }
1880 shr_assign_impl! { $t, usize }
1882 shr_assign_impl! { $t, i8 }
1883 shr_assign_impl! { $t, i16 }
1884 shr_assign_impl! { $t, i32 }
1885 shr_assign_impl! { $t, i64 }
1886 shr_assign_impl! { $t, i128 }
1887 shr_assign_impl! { $t, isize }
1891 shr_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1893 /// The `Index` trait is used to specify the functionality of indexing operations
1894 /// like `container[index]` when used in an immutable context.
1896 /// `container[index]` is actually syntactic sugar for `*container.index(index)`,
1897 /// but only when used as an immutable value. If a mutable value is requested,
1898 /// [`IndexMut`] is used instead. This allows nice things such as
1899 /// `let value = v[index]` if `value` implements [`Copy`].
1901 /// [`IndexMut`]: ../../std/ops/trait.IndexMut.html
1902 /// [`Copy`]: ../../std/marker/trait.Copy.html
1906 /// The following example implements `Index` on a read-only `NucleotideCount`
1907 /// container, enabling individual counts to be retrieved with index syntax.
1910 /// use std::ops::Index;
1912 /// enum Nucleotide {
1919 /// struct NucleotideCount {
1926 /// impl Index<Nucleotide> for NucleotideCount {
1927 /// type Output = usize;
1929 /// fn index(&self, nucleotide: Nucleotide) -> &usize {
1930 /// match nucleotide {
1931 /// Nucleotide::A => &self.a,
1932 /// Nucleotide::C => &self.c,
1933 /// Nucleotide::G => &self.g,
1934 /// Nucleotide::T => &self.t,
1939 /// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
1940 /// assert_eq!(nucleotide_count[Nucleotide::A], 14);
1941 /// assert_eq!(nucleotide_count[Nucleotide::C], 9);
1942 /// assert_eq!(nucleotide_count[Nucleotide::G], 10);
1943 /// assert_eq!(nucleotide_count[Nucleotide::T], 12);
1946 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 pub trait Index<Idx: ?Sized> {
1949 /// The returned type after indexing
1950 #[stable(feature = "rust1", since = "1.0.0")]
1951 type Output: ?Sized;
1953 /// The method for the indexing (`container[index]`) operation
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 fn index(&self, index: Idx) -> &Self::Output;
1958 /// The `IndexMut` trait is used to specify the functionality of indexing
1959 /// operations like `container[index]` when used in a mutable context.
1961 /// `container[index]` is actually syntactic sugar for
1962 /// `*container.index_mut(index)`, but only when used as a mutable value. If
1963 /// an immutable value is requested, the [`Index`] trait is used instead. This
1964 /// allows nice things such as `v[index] = value` if `value` implements [`Copy`].
1966 /// [`Index`]: ../../std/ops/trait.Index.html
1967 /// [`Copy`]: ../../std/marker/trait.Copy.html
1971 /// A very simple implementation of a `Balance` struct that has two sides, where
1972 /// each can be indexed mutably and immutably.
1975 /// use std::ops::{Index,IndexMut};
1977 /// #[derive(Debug)]
1983 /// #[derive(Debug, PartialEq)]
1989 /// struct Balance {
1990 /// pub left: Weight,
1991 /// pub right:Weight,
1994 /// impl Index<Side> for Balance {
1995 /// type Output = Weight;
1997 /// fn index<'a>(&'a self, index: Side) -> &'a Weight {
1998 /// println!("Accessing {:?}-side of balance immutably", index);
2000 /// Side::Left => &self.left,
2001 /// Side::Right => &self.right,
2006 /// impl IndexMut<Side> for Balance {
2007 /// fn index_mut<'a>(&'a mut self, index: Side) -> &'a mut Weight {
2008 /// println!("Accessing {:?}-side of balance mutably", index);
2010 /// Side::Left => &mut self.left,
2011 /// Side::Right => &mut self.right,
2017 /// let mut balance = Balance {
2018 /// right: Weight::Kilogram(2.5),
2019 /// left: Weight::Pound(1.5),
2022 /// // In this case balance[Side::Right] is sugar for
2023 /// // *balance.index(Side::Right), since we are only reading
2024 /// // balance[Side::Right], not writing it.
2025 /// assert_eq!(balance[Side::Right],Weight::Kilogram(2.5));
2027 /// // However in this case balance[Side::Left] is sugar for
2028 /// // *balance.index_mut(Side::Left), since we are writing
2029 /// // balance[Side::Left].
2030 /// balance[Side::Left] = Weight::Kilogram(3.0);
2033 #[lang = "index_mut"]
2034 #[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
2035 #[stable(feature = "rust1", since = "1.0.0")]
2036 pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
2037 /// The method for the mutable indexing (`container[index]`) operation
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
2042 /// An unbounded range. Use `..` (two dots) for its shorthand.
2044 /// Its primary use case is slicing index. It cannot serve as an iterator
2045 /// because it doesn't have a starting point.
2049 /// The `..` syntax is a `RangeFull`:
2052 /// assert_eq!((..), std::ops::RangeFull);
2055 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2056 /// `for` loop directly. This won't compile:
2064 /// Used as a slicing index, `RangeFull` produces the full array as a slice.
2067 /// let arr = [0, 1, 2, 3];
2068 /// assert_eq!(arr[ .. ], [0,1,2,3]); // RangeFull
2069 /// assert_eq!(arr[ ..3], [0,1,2 ]);
2070 /// assert_eq!(arr[1.. ], [ 1,2,3]);
2071 /// assert_eq!(arr[1..3], [ 1,2 ]);
2073 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2074 #[stable(feature = "rust1", since = "1.0.0")]
2075 pub struct RangeFull;
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 impl fmt::Debug for RangeFull {
2079 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2084 /// A (half-open) range which is bounded at both ends: { x | start <= x < end }.
2085 /// Use `start..end` (two dots) for its shorthand.
2087 /// See the [`contains`](#method.contains) method for its characterization.
2093 /// assert_eq!((3..5), std::ops::Range{ start: 3, end: 5 });
2094 /// assert_eq!(3+4+5, (3..6).sum());
2096 /// let arr = [0, 1, 2, 3];
2097 /// assert_eq!(arr[ .. ], [0,1,2,3]);
2098 /// assert_eq!(arr[ ..3], [0,1,2 ]);
2099 /// assert_eq!(arr[1.. ], [ 1,2,3]);
2100 /// assert_eq!(arr[1..3], [ 1,2 ]); // Range
2103 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 pub struct Range<Idx> {
2106 /// The lower bound of the range (inclusive).
2107 #[stable(feature = "rust1", since = "1.0.0")]
2109 /// The upper bound of the range (exclusive).
2110 #[stable(feature = "rust1", since = "1.0.0")]
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
2116 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2117 write!(fmt, "{:?}..{:?}", self.start, self.end)
2121 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2122 impl<Idx: PartialOrd<Idx>> Range<Idx> {
2126 /// #![feature(range_contains)]
2128 /// assert!( ! (3..5).contains(2));
2129 /// assert!( (3..5).contains(3));
2130 /// assert!( (3..5).contains(4));
2131 /// assert!( ! (3..5).contains(5));
2133 /// assert!( ! (3..3).contains(3));
2134 /// assert!( ! (3..2).contains(3));
2137 pub fn contains(&self, item: Idx) -> bool {
2138 (self.start <= item) && (item < self.end)
2142 /// A range which is only bounded below: { x | start <= x }.
2143 /// Use `start..` for its shorthand.
2145 /// See the [`contains`](#method.contains) method for its characterization.
2147 /// Note: Currently, no overflow checking is done for the iterator
2148 /// implementation; if you use an integer range and the integer overflows, it
2149 /// might panic in debug mode or create an endless loop in release mode. This
2150 /// overflow behavior might change in the future.
2156 /// assert_eq!((2..), std::ops::RangeFrom{ start: 2 });
2157 /// assert_eq!(2+3+4, (2..).take(3).sum());
2159 /// let arr = [0, 1, 2, 3];
2160 /// assert_eq!(arr[ .. ], [0,1,2,3]);
2161 /// assert_eq!(arr[ ..3], [0,1,2 ]);
2162 /// assert_eq!(arr[1.. ], [ 1,2,3]); // RangeFrom
2163 /// assert_eq!(arr[1..3], [ 1,2 ]);
2166 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 pub struct RangeFrom<Idx> {
2169 /// The lower bound of the range (inclusive).
2170 #[stable(feature = "rust1", since = "1.0.0")]
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
2176 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2177 write!(fmt, "{:?}..", self.start)
2181 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2182 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
2186 /// #![feature(range_contains)]
2188 /// assert!( ! (3..).contains(2));
2189 /// assert!( (3..).contains(3));
2190 /// assert!( (3..).contains(1_000_000_000));
2193 pub fn contains(&self, item: Idx) -> bool {
2194 (self.start <= item)
2198 /// A range which is only bounded above: { x | x < end }.
2199 /// Use `..end` (two dots) for its shorthand.
2201 /// See the [`contains`](#method.contains) method for its characterization.
2203 /// It cannot serve as an iterator because it doesn't have a starting point.
2207 /// The `..{integer}` syntax is a `RangeTo`:
2210 /// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
2213 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2214 /// `for` loop directly. This won't compile:
2222 /// When used as a slicing index, `RangeTo` produces a slice of all array
2223 /// elements before the index indicated by `end`.
2226 /// let arr = [0, 1, 2, 3];
2227 /// assert_eq!(arr[ .. ], [0,1,2,3]);
2228 /// assert_eq!(arr[ ..3], [0,1,2 ]); // RangeTo
2229 /// assert_eq!(arr[1.. ], [ 1,2,3]);
2230 /// assert_eq!(arr[1..3], [ 1,2 ]);
2232 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 pub struct RangeTo<Idx> {
2235 /// The upper bound of the range (exclusive).
2236 #[stable(feature = "rust1", since = "1.0.0")]
2240 #[stable(feature = "rust1", since = "1.0.0")]
2241 impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
2242 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2243 write!(fmt, "..{:?}", self.end)
2247 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2248 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
2252 /// #![feature(range_contains)]
2254 /// assert!( (..5).contains(-1_000_000_000));
2255 /// assert!( (..5).contains(4));
2256 /// assert!( ! (..5).contains(5));
2259 pub fn contains(&self, item: Idx) -> bool {
2264 /// An inclusive range which is bounded at both ends: { x | start <= x <= end }.
2265 /// Use `start...end` (three dots) for its shorthand.
2267 /// See the [`contains`](#method.contains) method for its characterization.
2272 /// #![feature(inclusive_range,inclusive_range_syntax)]
2274 /// assert_eq!((3...5), std::ops::RangeInclusive{ start: 3, end: 5 });
2275 /// assert_eq!(3+4+5, (3...5).sum());
2277 /// let arr = [0, 1, 2, 3];
2278 /// assert_eq!(arr[ ...2], [0,1,2 ]);
2279 /// assert_eq!(arr[1...2], [ 1,2 ]); // RangeInclusive
2282 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
2283 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2284 pub struct RangeInclusive<Idx> {
2285 /// The lower bound of the range (inclusive).
2286 #[unstable(feature = "inclusive_range",
2287 reason = "recently added, follows RFC",
2290 /// The upper bound of the range (inclusive).
2291 #[unstable(feature = "inclusive_range",
2292 reason = "recently added, follows RFC",
2297 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2298 impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
2299 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2300 write!(fmt, "{:?}...{:?}", self.start, self.end)
2304 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2305 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
2309 /// #![feature(range_contains,inclusive_range_syntax)]
2311 /// assert!( ! (3...5).contains(2));
2312 /// assert!( (3...5).contains(3));
2313 /// assert!( (3...5).contains(4));
2314 /// assert!( (3...5).contains(5));
2315 /// assert!( ! (3...5).contains(6));
2317 /// assert!( (3...3).contains(3));
2318 /// assert!( ! (3...2).contains(3));
2321 pub fn contains(&self, item: Idx) -> bool {
2322 self.start <= item && item <= self.end
2326 /// An inclusive range which is only bounded above: { x | x <= end }.
2327 /// Use `...end` (three dots) for its shorthand.
2329 /// See the [`contains`](#method.contains) method for its characterization.
2331 /// It cannot serve as an iterator because it doesn't have a starting point.
2335 /// The `...{integer}` syntax is a `RangeToInclusive`:
2338 /// #![feature(inclusive_range,inclusive_range_syntax)]
2339 /// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
2342 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2343 /// `for` loop directly. This won't compile:
2351 /// When used as a slicing index, `RangeToInclusive` produces a slice of all
2352 /// array elements up to and including the index indicated by `end`.
2355 /// #![feature(inclusive_range_syntax)]
2356 /// let arr = [0, 1, 2, 3];
2357 /// assert_eq!(arr[ ...2], [0,1,2 ]); // RangeToInclusive
2358 /// assert_eq!(arr[1...2], [ 1,2 ]);
2360 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2361 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2362 pub struct RangeToInclusive<Idx> {
2363 /// The upper bound of the range (inclusive)
2364 #[unstable(feature = "inclusive_range",
2365 reason = "recently added, follows RFC",
2370 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2371 impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
2372 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2373 write!(fmt, "...{:?}", self.end)
2377 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2378 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
2382 /// #![feature(range_contains,inclusive_range_syntax)]
2384 /// assert!( (...5).contains(-1_000_000_000));
2385 /// assert!( (...5).contains(5));
2386 /// assert!( ! (...5).contains(6));
2389 pub fn contains(&self, item: Idx) -> bool {
2394 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
2395 // because underflow would be possible with (..0).into()
2397 /// The `Deref` trait is used to specify the functionality of dereferencing
2398 /// operations, like `*v`.
2400 /// `Deref` also enables ['`Deref` coercions'][coercions].
2402 /// [coercions]: ../../book/deref-coercions.html
2406 /// A struct with a single field which is accessible via dereferencing the
2410 /// use std::ops::Deref;
2412 /// struct DerefExample<T> {
2416 /// impl<T> Deref for DerefExample<T> {
2417 /// type Target = T;
2419 /// fn deref(&self) -> &T {
2425 /// let x = DerefExample { value: 'a' };
2426 /// assert_eq!('a', *x);
2430 #[stable(feature = "rust1", since = "1.0.0")]
2432 /// The resulting type after dereferencing
2433 #[stable(feature = "rust1", since = "1.0.0")]
2434 type Target: ?Sized;
2436 /// The method called to dereference a value
2437 #[stable(feature = "rust1", since = "1.0.0")]
2438 fn deref(&self) -> &Self::Target;
2441 #[stable(feature = "rust1", since = "1.0.0")]
2442 impl<'a, T: ?Sized> Deref for &'a T {
2445 fn deref(&self) -> &T { *self }
2448 #[stable(feature = "rust1", since = "1.0.0")]
2449 impl<'a, T: ?Sized> Deref for &'a mut T {
2452 fn deref(&self) -> &T { *self }
2455 /// The `DerefMut` trait is used to specify the functionality of dereferencing
2456 /// mutably like `*v = 1;`
2458 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
2460 /// [coercions]: ../../book/deref-coercions.html
2464 /// A struct with a single field which is modifiable via dereferencing the
2468 /// use std::ops::{Deref, DerefMut};
2470 /// struct DerefMutExample<T> {
2474 /// impl<T> Deref for DerefMutExample<T> {
2475 /// type Target = T;
2477 /// fn deref(&self) -> &T {
2482 /// impl<T> DerefMut for DerefMutExample<T> {
2483 /// fn deref_mut(&mut self) -> &mut T {
2489 /// let mut x = DerefMutExample { value: 'a' };
2491 /// assert_eq!('b', *x);
2494 #[lang = "deref_mut"]
2495 #[stable(feature = "rust1", since = "1.0.0")]
2496 pub trait DerefMut: Deref {
2497 /// The method called to mutably dereference a value
2498 #[stable(feature = "rust1", since = "1.0.0")]
2499 fn deref_mut(&mut self) -> &mut Self::Target;
2502 #[stable(feature = "rust1", since = "1.0.0")]
2503 impl<'a, T: ?Sized> DerefMut for &'a mut T {
2504 fn deref_mut(&mut self) -> &mut T { *self }
2507 /// A version of the call operator that takes an immutable receiver.
2511 /// Closures automatically implement this trait, which allows them to be
2512 /// invoked. Note, however, that `Fn` takes an immutable reference to any
2513 /// captured variables. To take a mutable capture, implement [`FnMut`], and to
2514 /// consume the capture, implement [`FnOnce`].
2516 /// [`FnMut`]: trait.FnMut.html
2517 /// [`FnOnce`]: trait.FnOnce.html
2520 /// let square = |x| x * x;
2521 /// assert_eq!(square(5), 25);
2524 /// Closures can also be passed to higher-level functions through a `Fn`
2525 /// parameter (or a `FnMut` or `FnOnce` parameter, which are supertraits of
2529 /// fn call_with_one<F>(func: F) -> usize
2530 /// where F: Fn(usize) -> usize {
2534 /// let double = |x| x * 2;
2535 /// assert_eq!(call_with_one(double), 2);
2538 #[stable(feature = "rust1", since = "1.0.0")]
2539 #[rustc_paren_sugar]
2540 #[fundamental] // so that regex can rely that `&str: !FnMut`
2541 pub trait Fn<Args> : FnMut<Args> {
2542 /// This is called when the call operator is used.
2543 #[unstable(feature = "fn_traits", issue = "29625")]
2544 extern "rust-call" fn call(&self, args: Args) -> Self::Output;
2547 /// A version of the call operator that takes a mutable receiver.
2551 /// Closures that mutably capture variables automatically implement this trait,
2552 /// which allows them to be invoked.
2557 /// let mut square_x = || x *= x;
2560 /// assert_eq!(x, 25);
2563 /// Closures can also be passed to higher-level functions through a `FnMut`
2564 /// parameter (or a `FnOnce` parameter, which is a supertrait of `FnMut`).
2567 /// fn do_twice<F>(mut func: F)
2568 /// where F: FnMut()
2574 /// let mut x: usize = 1;
2576 /// let add_two_to_x = || x += 2;
2577 /// do_twice(add_two_to_x);
2580 /// assert_eq!(x, 5);
2583 #[stable(feature = "rust1", since = "1.0.0")]
2584 #[rustc_paren_sugar]
2585 #[fundamental] // so that regex can rely that `&str: !FnMut`
2586 pub trait FnMut<Args> : FnOnce<Args> {
2587 /// This is called when the call operator is used.
2588 #[unstable(feature = "fn_traits", issue = "29625")]
2589 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
2592 /// A version of the call operator that takes a by-value receiver.
2596 /// By-value closures automatically implement this trait, which allows them to
2601 /// let square_x = move || x * x;
2602 /// assert_eq!(square_x(), 25);
2605 /// By-value Closures can also be passed to higher-level functions through a
2606 /// `FnOnce` parameter.
2609 /// fn consume_with_relish<F>(func: F)
2610 /// where F: FnOnce() -> String
2612 /// // `func` consumes its captured variables, so it cannot be run more
2614 /// println!("Consumed: {}", func());
2616 /// println!("Delicious!");
2618 /// // Attempting to invoke `func()` again will throw a `use of moved
2619 /// // value` error for `func`
2622 /// let x = String::from("x");
2623 /// let consume_and_return_x = move || x;
2624 /// consume_with_relish(consume_and_return_x);
2626 /// // `consume_and_return_x` can no longer be invoked at this point
2629 #[stable(feature = "rust1", since = "1.0.0")]
2630 #[rustc_paren_sugar]
2631 #[fundamental] // so that regex can rely that `&str: !FnMut`
2632 pub trait FnOnce<Args> {
2633 /// The returned type after the call operator is used.
2634 #[stable(feature = "fn_once_output", since = "1.12.0")]
2637 /// This is called when the call operator is used.
2638 #[unstable(feature = "fn_traits", issue = "29625")]
2639 extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
2643 #[stable(feature = "rust1", since = "1.0.0")]
2644 impl<'a,A,F:?Sized> Fn<A> for &'a F
2647 extern "rust-call" fn call(&self, args: A) -> F::Output {
2652 #[stable(feature = "rust1", since = "1.0.0")]
2653 impl<'a,A,F:?Sized> FnMut<A> for &'a F
2656 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2661 #[stable(feature = "rust1", since = "1.0.0")]
2662 impl<'a,A,F:?Sized> FnOnce<A> for &'a F
2665 type Output = F::Output;
2667 extern "rust-call" fn call_once(self, args: A) -> F::Output {
2672 #[stable(feature = "rust1", since = "1.0.0")]
2673 impl<'a,A,F:?Sized> FnMut<A> for &'a mut F
2676 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2677 (*self).call_mut(args)
2681 #[stable(feature = "rust1", since = "1.0.0")]
2682 impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F
2685 type Output = F::Output;
2686 extern "rust-call" fn call_once(mut self, args: A) -> F::Output {
2687 (*self).call_mut(args)
2692 /// Trait that indicates that this is a pointer or a wrapper for one,
2693 /// where unsizing can be performed on the pointee.
2695 /// See the [DST coercion RfC][dst-coerce] and [the nomicon entry on coercion][nomicon-coerce]
2696 /// for more details.
2698 /// For builtin pointer types, pointers to `T` will coerce to pointers to `U` if `T: Unsize<U>`
2699 /// by converting from a thin pointer to a fat pointer.
2701 /// For custom types, the coercion here works by coercing `Foo<T>` to `Foo<U>`
2702 /// provided an impl of `CoerceUnsized<Foo<U>> for Foo<T>` exists.
2703 /// Such an impl can only be written if `Foo<T>` has only a single non-phantomdata
2704 /// field involving `T`. If the type of that field is `Bar<T>`, an implementation
2705 /// of `CoerceUnsized<Bar<U>> for Bar<T>` must exist. The coercion will work by
2706 /// by coercing the `Bar<T>` field into `Bar<U>` and filling in the rest of the fields
2707 /// from `Foo<T>` to create a `Foo<U>`. This will effectively drill down to a pointer
2708 /// field and coerce that.
2710 /// Generally, for smart pointers you will implement
2711 /// `CoerceUnsized<Ptr<U>> for Ptr<T> where T: Unsize<U>, U: ?Sized`, with an
2712 /// optional `?Sized` bound on `T` itself. For wrapper types that directly embed `T`
2713 /// like `Cell<T>` and `RefCell<T>`, you
2714 /// can directly implement `CoerceUnsized<Wrap<U>> for Wrap<T> where T: CoerceUnsized<U>`.
2715 /// This will let coercions of types like `Cell<Box<T>>` work.
2717 /// [`Unsize`][unsize] is used to mark types which can be coerced to DSTs if behind
2718 /// pointers. It is implemented automatically by the compiler.
2720 /// [dst-coerce]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2721 /// [unsize]: ../marker/trait.Unsize.html
2722 /// [nomicon-coerce]: ../../nomicon/coercions.html
2723 #[unstable(feature = "coerce_unsized", issue = "27732")]
2724 #[lang="coerce_unsized"]
2725 pub trait CoerceUnsized<T> {
2730 #[unstable(feature = "coerce_unsized", issue = "27732")]
2731 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a mut U> for &'a mut T {}
2733 #[unstable(feature = "coerce_unsized", issue = "27732")]
2734 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b mut T {}
2736 #[unstable(feature = "coerce_unsized", issue = "27732")]
2737 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for &'a mut T {}
2738 // &mut T -> *const U
2739 #[unstable(feature = "coerce_unsized", issue = "27732")]
2740 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a mut T {}
2743 #[unstable(feature = "coerce_unsized", issue = "27732")]
2744 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
2746 #[unstable(feature = "coerce_unsized", issue = "27732")]
2747 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a T {}
2750 #[unstable(feature = "coerce_unsized", issue = "27732")]
2751 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for *mut T {}
2752 // *mut T -> *const U
2753 #[unstable(feature = "coerce_unsized", issue = "27732")]
2754 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *mut T {}
2756 // *const T -> *const U
2757 #[unstable(feature = "coerce_unsized", issue = "27732")]
2758 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *const T {}
2760 /// Both `PLACE <- EXPR` and `box EXPR` desugar into expressions
2761 /// that allocate an intermediate "place" that holds uninitialized
2762 /// state. The desugaring evaluates EXPR, and writes the result at
2763 /// the address returned by the `pointer` method of this trait.
2765 /// A `Place` can be thought of as a special representation for a
2766 /// hypothetical `&uninit` reference (which Rust cannot currently
2767 /// express directly). That is, it represents a pointer to
2768 /// uninitialized storage.
2770 /// The client is responsible for two steps: First, initializing the
2771 /// payload (it can access its address via `pointer`). Second,
2772 /// converting the agent to an instance of the owning pointer, via the
2773 /// appropriate `finalize` method (see the `InPlace`.
2775 /// If evaluating EXPR fails, then it is up to the destructor for the
2776 /// implementation of Place to clean up any intermediate state
2777 /// (e.g. deallocate box storage, pop a stack, etc).
2778 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2779 pub trait Place<Data: ?Sized> {
2780 /// Returns the address where the input value will be written.
2781 /// Note that the data at this address is generally uninitialized,
2782 /// and thus one should use `ptr::write` for initializing it.
2783 fn pointer(&mut self) -> *mut Data;
2786 /// Interface to implementations of `PLACE <- EXPR`.
2788 /// `PLACE <- EXPR` effectively desugars into:
2792 /// let mut place = Placer::make_place(p);
2793 /// let raw_place = Place::pointer(&mut place);
2794 /// let value = EXPR;
2796 /// std::ptr::write(raw_place, value);
2797 /// InPlace::finalize(place)
2801 /// The type of `PLACE <- EXPR` is derived from the type of `PLACE`;
2802 /// if the type of `PLACE` is `P`, then the final type of the whole
2803 /// expression is `P::Place::Owner` (see the `InPlace` and `Boxed`
2806 /// Values for types implementing this trait usually are transient
2807 /// intermediate values (e.g. the return value of `Vec::emplace_back`)
2808 /// or `Copy`, since the `make_place` method takes `self` by value.
2809 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2810 pub trait Placer<Data: ?Sized> {
2811 /// `Place` is the intermedate agent guarding the
2812 /// uninitialized state for `Data`.
2813 type Place: InPlace<Data>;
2815 /// Creates a fresh place from `self`.
2816 fn make_place(self) -> Self::Place;
2819 /// Specialization of `Place` trait supporting `PLACE <- EXPR`.
2820 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2821 pub trait InPlace<Data: ?Sized>: Place<Data> {
2822 /// `Owner` is the type of the end value of `PLACE <- EXPR`
2824 /// Note that when `PLACE <- EXPR` is solely used for
2825 /// side-effecting an existing data-structure,
2826 /// e.g. `Vec::emplace_back`, then `Owner` need not carry any
2827 /// information at all (e.g. it can be the unit type `()` in that
2831 /// Converts self into the final value, shifting
2832 /// deallocation/cleanup responsibilities (if any remain), over to
2833 /// the returned instance of `Owner` and forgetting self.
2834 unsafe fn finalize(self) -> Self::Owner;
2837 /// Core trait for the `box EXPR` form.
2839 /// `box EXPR` effectively desugars into:
2842 /// let mut place = BoxPlace::make_place();
2843 /// let raw_place = Place::pointer(&mut place);
2844 /// let value = EXPR;
2846 /// ::std::ptr::write(raw_place, value);
2847 /// Boxed::finalize(place)
2851 /// The type of `box EXPR` is supplied from its surrounding
2852 /// context; in the above expansion, the result type `T` is used
2853 /// to determine which implementation of `Boxed` to use, and that
2854 /// `<T as Boxed>` in turn dictates determines which
2855 /// implementation of `BoxPlace` to use, namely:
2856 /// `<<T as Boxed>::Place as BoxPlace>`.
2857 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2859 /// The kind of data that is stored in this kind of box.
2860 type Data; /* (`Data` unused b/c cannot yet express below bound.) */
2861 /// The place that will negotiate the storage of the data.
2862 type Place: BoxPlace<Self::Data>;
2864 /// Converts filled place into final owning value, shifting
2865 /// deallocation/cleanup responsibilities (if any remain), over to
2866 /// returned instance of `Self` and forgetting `filled`.
2867 unsafe fn finalize(filled: Self::Place) -> Self;
2870 /// Specialization of `Place` trait supporting `box EXPR`.
2871 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2872 pub trait BoxPlace<Data: ?Sized> : Place<Data> {
2873 /// Creates a globally fresh place.
2874 fn make_place() -> Self;
2877 /// A trait for types which have success and error states and are meant to work
2878 /// with the question mark operator.
2879 /// When the `?` operator is used with a value, whether the value is in the
2880 /// success or error state is determined by calling `translate`.
2882 /// This trait is **very** experimental, it will probably be iterated on heavily
2883 /// before it is stabilised. Implementors should expect change. Users of `?`
2884 /// should not rely on any implementations of `Carrier` other than `Result`,
2885 /// i.e., you should not expect `?` to continue to work with `Option`, etc.
2886 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2888 /// The type of the value when computation succeeds.
2890 /// The type of the value when computation errors out.
2893 /// Create a `Carrier` from a success value.
2894 fn from_success(_: Self::Success) -> Self;
2896 /// Create a `Carrier` from an error value.
2897 fn from_error(_: Self::Error) -> Self;
2899 /// Translate this `Carrier` to another implementation of `Carrier` with the
2900 /// same associated types.
2901 fn translate<T>(self) -> T where T: Carrier<Success=Self::Success, Error=Self::Error>;
2904 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2905 impl<U, V> Carrier for Result<U, V> {
2909 fn from_success(u: U) -> Result<U, V> {
2913 fn from_error(e: V) -> Result<U, V> {
2917 fn translate<T>(self) -> T
2918 where T: Carrier<Success=U, Error=V>
2921 Ok(u) => T::from_success(u),
2922 Err(e) => T::from_error(e),
2927 struct _DummyErrorType;
2929 impl Carrier for _DummyErrorType {
2933 fn from_success(_: ()) -> _DummyErrorType {
2937 fn from_error(_: ()) -> _DummyErrorType {
2941 fn translate<T>(self) -> T
2942 where T: Carrier<Success=(), Error=()>