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 macro_rules! neg_impl_unsigned {
804 neg_impl_core!{ x => {
809 // neg_impl_unsigned! { usize u8 u16 u32 u64 }
810 neg_impl_numeric! { isize i8 i16 i32 i64 i128 f32 f64 }
812 /// The unary logical negation operator `!`.
816 /// An implementation of `Not` for `Answer`, which enables the use of `!` to
817 /// invert its value.
820 /// use std::ops::Not;
822 /// #[derive(Debug, PartialEq)]
828 /// impl Not for Answer {
829 /// type Output = Answer;
831 /// fn not(self) -> Answer {
833 /// Answer::Yes => Answer::No,
834 /// Answer::No => Answer::Yes
839 /// assert_eq!(!Answer::Yes, Answer::No);
840 /// assert_eq!(!Answer::No, Answer::Yes);
843 #[stable(feature = "rust1", since = "1.0.0")]
845 /// The resulting type after applying the `!` operator
846 #[stable(feature = "rust1", since = "1.0.0")]
849 /// The method for the unary `!` operator
850 #[stable(feature = "rust1", since = "1.0.0")]
851 fn not(self) -> Self::Output;
854 macro_rules! not_impl {
856 #[stable(feature = "rust1", since = "1.0.0")]
861 fn not(self) -> $t { !self }
864 forward_ref_unop! { impl Not, not for $t }
868 not_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
870 /// The bitwise AND operator `&`.
874 /// In this example, the `&` operator is lifted to a trivial `Scalar` type.
877 /// use std::ops::BitAnd;
879 /// #[derive(Debug, PartialEq)]
880 /// struct Scalar(bool);
882 /// impl BitAnd for Scalar {
883 /// type Output = Self;
885 /// // rhs is the "right-hand side" of the expression `a & b`
886 /// fn bitand(self, rhs: Self) -> Self {
887 /// Scalar(self.0 & rhs.0)
892 /// assert_eq!(Scalar(true) & Scalar(true), Scalar(true));
893 /// assert_eq!(Scalar(true) & Scalar(false), Scalar(false));
894 /// assert_eq!(Scalar(false) & Scalar(true), Scalar(false));
895 /// assert_eq!(Scalar(false) & Scalar(false), Scalar(false));
899 /// In this example, the `BitAnd` trait is implemented for a `BooleanVector`
903 /// use std::ops::BitAnd;
905 /// #[derive(Debug, PartialEq)]
906 /// struct BooleanVector(Vec<bool>);
908 /// impl BitAnd for BooleanVector {
909 /// type Output = Self;
911 /// fn bitand(self, BooleanVector(rhs): Self) -> Self {
912 /// let BooleanVector(lhs) = self;
913 /// assert_eq!(lhs.len(), rhs.len());
914 /// BooleanVector(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x && *y).collect())
919 /// let bv1 = BooleanVector(vec![true, true, false, false]);
920 /// let bv2 = BooleanVector(vec![true, false, true, false]);
921 /// let expected = BooleanVector(vec![true, false, false, false]);
922 /// assert_eq!(bv1 & bv2, expected);
926 #[stable(feature = "rust1", since = "1.0.0")]
927 #[rustc_on_unimplemented = "no implementation for `{Self} & {RHS}`"]
928 pub trait BitAnd<RHS=Self> {
929 /// The resulting type after applying the `&` operator
930 #[stable(feature = "rust1", since = "1.0.0")]
933 /// The method for the `&` operator
934 #[stable(feature = "rust1", since = "1.0.0")]
935 fn bitand(self, rhs: RHS) -> Self::Output;
938 macro_rules! bitand_impl {
940 #[stable(feature = "rust1", since = "1.0.0")]
945 fn bitand(self, rhs: $t) -> $t { self & rhs }
948 forward_ref_binop! { impl BitAnd, bitand for $t, $t }
952 bitand_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
954 /// The bitwise OR operator `|`.
958 /// In this example, the `|` operator is lifted to a trivial `Scalar` type.
961 /// use std::ops::BitOr;
963 /// #[derive(Debug, PartialEq)]
964 /// struct Scalar(bool);
966 /// impl BitOr for Scalar {
967 /// type Output = Self;
969 /// // rhs is the "right-hand side" of the expression `a | b`
970 /// fn bitor(self, rhs: Self) -> Self {
971 /// Scalar(self.0 | rhs.0)
976 /// assert_eq!(Scalar(true) | Scalar(true), Scalar(true));
977 /// assert_eq!(Scalar(true) | Scalar(false), Scalar(true));
978 /// assert_eq!(Scalar(false) | Scalar(true), Scalar(true));
979 /// assert_eq!(Scalar(false) | Scalar(false), Scalar(false));
983 /// In this example, the `BitOr` trait is implemented for a `BooleanVector`
987 /// use std::ops::BitOr;
989 /// #[derive(Debug, PartialEq)]
990 /// struct BooleanVector(Vec<bool>);
992 /// impl BitOr for BooleanVector {
993 /// type Output = Self;
995 /// fn bitor(self, BooleanVector(rhs): Self) -> Self {
996 /// let BooleanVector(lhs) = self;
997 /// assert_eq!(lhs.len(), rhs.len());
998 /// BooleanVector(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x || *y).collect())
1003 /// let bv1 = BooleanVector(vec![true, true, false, false]);
1004 /// let bv2 = BooleanVector(vec![true, false, true, false]);
1005 /// let expected = BooleanVector(vec![true, true, true, false]);
1006 /// assert_eq!(bv1 | bv2, expected);
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 #[rustc_on_unimplemented = "no implementation for `{Self} | {RHS}`"]
1012 pub trait BitOr<RHS=Self> {
1013 /// The resulting type after applying the `|` operator
1014 #[stable(feature = "rust1", since = "1.0.0")]
1017 /// The method for the `|` operator
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 fn bitor(self, rhs: RHS) -> Self::Output;
1022 macro_rules! bitor_impl {
1024 #[stable(feature = "rust1", since = "1.0.0")]
1029 fn bitor(self, rhs: $t) -> $t { self | rhs }
1032 forward_ref_binop! { impl BitOr, bitor for $t, $t }
1036 bitor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1038 /// The bitwise XOR operator `^`.
1042 /// In this example, the `^` operator is lifted to a trivial `Scalar` type.
1045 /// use std::ops::BitXor;
1047 /// #[derive(Debug, PartialEq)]
1048 /// struct Scalar(bool);
1050 /// impl BitXor for Scalar {
1051 /// type Output = Self;
1053 /// // rhs is the "right-hand side" of the expression `a ^ b`
1054 /// fn bitxor(self, rhs: Self) -> Self {
1055 /// Scalar(self.0 ^ rhs.0)
1060 /// assert_eq!(Scalar(true) ^ Scalar(true), Scalar(false));
1061 /// assert_eq!(Scalar(true) ^ Scalar(false), Scalar(true));
1062 /// assert_eq!(Scalar(false) ^ Scalar(true), Scalar(true));
1063 /// assert_eq!(Scalar(false) ^ Scalar(false), Scalar(false));
1067 /// In this example, the `BitXor` trait is implemented for a `BooleanVector`
1071 /// use std::ops::BitXor;
1073 /// #[derive(Debug, PartialEq)]
1074 /// struct BooleanVector(Vec<bool>);
1076 /// impl BitXor for BooleanVector {
1077 /// type Output = Self;
1079 /// fn bitxor(self, BooleanVector(rhs): Self) -> Self {
1080 /// let BooleanVector(lhs) = self;
1081 /// assert_eq!(lhs.len(), rhs.len());
1082 /// BooleanVector(lhs.iter()
1083 /// .zip(rhs.iter())
1084 /// .map(|(x, y)| (*x || *y) && !(*x && *y))
1090 /// let bv1 = BooleanVector(vec![true, true, false, false]);
1091 /// let bv2 = BooleanVector(vec![true, false, true, false]);
1092 /// let expected = BooleanVector(vec![false, true, true, false]);
1093 /// assert_eq!(bv1 ^ bv2, expected);
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 #[rustc_on_unimplemented = "no implementation for `{Self} ^ {RHS}`"]
1099 pub trait BitXor<RHS=Self> {
1100 /// The resulting type after applying the `^` operator
1101 #[stable(feature = "rust1", since = "1.0.0")]
1104 /// The method for the `^` operator
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 fn bitxor(self, rhs: RHS) -> Self::Output;
1109 macro_rules! bitxor_impl {
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl BitXor for $t {
1116 fn bitxor(self, other: $t) -> $t { self ^ other }
1119 forward_ref_binop! { impl BitXor, bitxor for $t, $t }
1123 bitxor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1125 /// The left shift operator `<<`.
1129 /// An implementation of `Shl` that lifts the `<<` operation on integers to a
1130 /// `Scalar` struct.
1133 /// use std::ops::Shl;
1135 /// #[derive(PartialEq, Debug)]
1136 /// struct Scalar(usize);
1138 /// impl Shl<Scalar> for Scalar {
1139 /// type Output = Self;
1141 /// fn shl(self, Scalar(rhs): Self) -> Scalar {
1142 /// let Scalar(lhs) = self;
1143 /// Scalar(lhs << rhs)
1147 /// assert_eq!(Scalar(4) << Scalar(2), Scalar(16));
1151 /// An implementation of `Shl` that spins a vector leftward by a given amount.
1154 /// use std::ops::Shl;
1156 /// #[derive(PartialEq, Debug)]
1157 /// struct SpinVector<T: Clone> {
1161 /// impl<T: Clone> Shl<usize> for SpinVector<T> {
1162 /// type Output = Self;
1164 /// fn shl(self, rhs: usize) -> SpinVector<T> {
1165 /// // rotate the vector by `rhs` places
1166 /// let (a, b) = self.vec.split_at(rhs);
1167 /// let mut spun_vector: Vec<T> = vec![];
1168 /// spun_vector.extend_from_slice(b);
1169 /// spun_vector.extend_from_slice(a);
1170 /// SpinVector { vec: spun_vector }
1175 /// assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } << 2,
1176 /// SpinVector { vec: vec![2, 3, 4, 0, 1] });
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 #[rustc_on_unimplemented = "no implementation for `{Self} << {RHS}`"]
1182 pub trait Shl<RHS> {
1183 /// The resulting type after applying the `<<` operator
1184 #[stable(feature = "rust1", since = "1.0.0")]
1187 /// The method for the `<<` operator
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 fn shl(self, rhs: RHS) -> Self::Output;
1192 macro_rules! shl_impl {
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 impl Shl<$f> for $t {
1199 #[rustc_inherit_overflow_checks]
1200 fn shl(self, other: $f) -> $t {
1205 forward_ref_binop! { impl Shl, shl for $t, $f }
1209 macro_rules! shl_impl_all {
1211 shl_impl! { $t, u8 }
1212 shl_impl! { $t, u16 }
1213 shl_impl! { $t, u32 }
1214 shl_impl! { $t, u64 }
1215 shl_impl! { $t, u128 }
1216 shl_impl! { $t, usize }
1218 shl_impl! { $t, i8 }
1219 shl_impl! { $t, i16 }
1220 shl_impl! { $t, i32 }
1221 shl_impl! { $t, i64 }
1222 shl_impl! { $t, i128 }
1223 shl_impl! { $t, isize }
1227 shl_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 isize i128 }
1229 /// The right shift operator `>>`.
1233 /// An implementation of `Shr` that lifts the `>>` operation on integers to a
1234 /// `Scalar` struct.
1237 /// use std::ops::Shr;
1239 /// #[derive(PartialEq, Debug)]
1240 /// struct Scalar(usize);
1242 /// impl Shr<Scalar> for Scalar {
1243 /// type Output = Self;
1245 /// fn shr(self, Scalar(rhs): Self) -> Scalar {
1246 /// let Scalar(lhs) = self;
1247 /// Scalar(lhs >> rhs)
1251 /// assert_eq!(Scalar(16) >> Scalar(2), Scalar(4));
1255 /// An implementation of `Shr` that spins a vector rightward by a given amount.
1258 /// use std::ops::Shr;
1260 /// #[derive(PartialEq, Debug)]
1261 /// struct SpinVector<T: Clone> {
1265 /// impl<T: Clone> Shr<usize> for SpinVector<T> {
1266 /// type Output = Self;
1268 /// fn shr(self, rhs: usize) -> SpinVector<T> {
1269 /// // rotate the vector by `rhs` places
1270 /// let (a, b) = self.vec.split_at(self.vec.len() - rhs);
1271 /// let mut spun_vector: Vec<T> = vec![];
1272 /// spun_vector.extend_from_slice(b);
1273 /// spun_vector.extend_from_slice(a);
1274 /// SpinVector { vec: spun_vector }
1279 /// assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } >> 2,
1280 /// SpinVector { vec: vec![3, 4, 0, 1, 2] });
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 #[rustc_on_unimplemented = "no implementation for `{Self} >> {RHS}`"]
1286 pub trait Shr<RHS> {
1287 /// The resulting type after applying the `>>` operator
1288 #[stable(feature = "rust1", since = "1.0.0")]
1291 /// The method for the `>>` operator
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 fn shr(self, rhs: RHS) -> Self::Output;
1296 macro_rules! shr_impl {
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 impl Shr<$f> for $t {
1303 #[rustc_inherit_overflow_checks]
1304 fn shr(self, other: $f) -> $t {
1309 forward_ref_binop! { impl Shr, shr for $t, $f }
1313 macro_rules! shr_impl_all {
1315 shr_impl! { $t, u8 }
1316 shr_impl! { $t, u16 }
1317 shr_impl! { $t, u32 }
1318 shr_impl! { $t, u64 }
1319 shr_impl! { $t, u128 }
1320 shr_impl! { $t, usize }
1322 shr_impl! { $t, i8 }
1323 shr_impl! { $t, i16 }
1324 shr_impl! { $t, i32 }
1325 shr_impl! { $t, i64 }
1326 shr_impl! { $t, i128 }
1327 shr_impl! { $t, isize }
1331 shr_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1333 /// The addition assignment operator `+=`.
1337 /// This example creates a `Point` struct that implements the `AddAssign`
1338 /// trait, and then demonstrates add-assigning to a mutable `Point`.
1341 /// use std::ops::AddAssign;
1343 /// #[derive(Debug)]
1349 /// impl AddAssign for Point {
1350 /// fn add_assign(&mut self, other: Point) {
1352 /// x: self.x + other.x,
1353 /// y: self.y + other.y,
1358 /// impl PartialEq for Point {
1359 /// fn eq(&self, other: &Self) -> bool {
1360 /// self.x == other.x && self.y == other.y
1364 /// let mut point = Point { x: 1, y: 0 };
1365 /// point += Point { x: 2, y: 3 };
1366 /// assert_eq!(point, Point { x: 3, y: 3 });
1368 #[lang = "add_assign"]
1369 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1370 #[rustc_on_unimplemented = "no implementation for `{Self} += {Rhs}`"]
1371 pub trait AddAssign<Rhs=Self> {
1372 /// The method for the `+=` operator
1373 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1374 fn add_assign(&mut self, rhs: Rhs);
1377 macro_rules! add_assign_impl {
1379 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1380 impl AddAssign for $t {
1382 #[rustc_inherit_overflow_checks]
1383 fn add_assign(&mut self, other: $t) { *self += other }
1388 add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1390 /// The subtraction assignment operator `-=`.
1394 /// This example creates a `Point` struct that implements the `SubAssign`
1395 /// trait, and then demonstrates sub-assigning to a mutable `Point`.
1398 /// use std::ops::SubAssign;
1400 /// #[derive(Debug)]
1406 /// impl SubAssign for Point {
1407 /// fn sub_assign(&mut self, other: Point) {
1409 /// x: self.x - other.x,
1410 /// y: self.y - other.y,
1415 /// impl PartialEq for Point {
1416 /// fn eq(&self, other: &Self) -> bool {
1417 /// self.x == other.x && self.y == other.y
1421 /// let mut point = Point { x: 3, y: 3 };
1422 /// point -= Point { x: 2, y: 3 };
1423 /// assert_eq!(point, Point {x: 1, y: 0});
1425 #[lang = "sub_assign"]
1426 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1427 #[rustc_on_unimplemented = "no implementation for `{Self} -= {Rhs}`"]
1428 pub trait SubAssign<Rhs=Self> {
1429 /// The method for the `-=` operator
1430 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1431 fn sub_assign(&mut self, rhs: Rhs);
1434 macro_rules! sub_assign_impl {
1436 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1437 impl SubAssign for $t {
1439 #[rustc_inherit_overflow_checks]
1440 fn sub_assign(&mut self, other: $t) { *self -= other }
1445 sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1447 /// The multiplication assignment operator `*=`.
1451 /// A trivial implementation of `MulAssign`. When `Foo *= Foo` happens, it ends up
1452 /// calling `mul_assign`, and therefore, `main` prints `Multiplying!`.
1455 /// use std::ops::MulAssign;
1459 /// impl MulAssign for Foo {
1460 /// fn mul_assign(&mut self, _rhs: Foo) {
1461 /// println!("Multiplying!");
1465 /// # #[allow(unused_assignments)]
1467 /// let mut foo = Foo;
1471 #[lang = "mul_assign"]
1472 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1473 #[rustc_on_unimplemented = "no implementation for `{Self} *= {Rhs}`"]
1474 pub trait MulAssign<Rhs=Self> {
1475 /// The method for the `*=` operator
1476 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1477 fn mul_assign(&mut self, rhs: Rhs);
1480 macro_rules! mul_assign_impl {
1482 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1483 impl MulAssign for $t {
1485 #[rustc_inherit_overflow_checks]
1486 fn mul_assign(&mut self, other: $t) { *self *= other }
1491 mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1493 /// The division assignment operator `/=`.
1497 /// A trivial implementation of `DivAssign`. When `Foo /= Foo` happens, it ends up
1498 /// calling `div_assign`, and therefore, `main` prints `Dividing!`.
1501 /// use std::ops::DivAssign;
1505 /// impl DivAssign for Foo {
1506 /// fn div_assign(&mut self, _rhs: Foo) {
1507 /// println!("Dividing!");
1511 /// # #[allow(unused_assignments)]
1513 /// let mut foo = Foo;
1517 #[lang = "div_assign"]
1518 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1519 #[rustc_on_unimplemented = "no implementation for `{Self} /= {Rhs}`"]
1520 pub trait DivAssign<Rhs=Self> {
1521 /// The method for the `/=` operator
1522 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1523 fn div_assign(&mut self, rhs: Rhs);
1526 macro_rules! div_assign_impl {
1528 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1529 impl DivAssign for $t {
1531 fn div_assign(&mut self, other: $t) { *self /= other }
1536 div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1538 /// The remainder assignment operator `%=`.
1542 /// A trivial implementation of `RemAssign`. When `Foo %= Foo` happens, it ends up
1543 /// calling `rem_assign`, and therefore, `main` prints `Remainder-ing!`.
1546 /// use std::ops::RemAssign;
1550 /// impl RemAssign for Foo {
1551 /// fn rem_assign(&mut self, _rhs: Foo) {
1552 /// println!("Remainder-ing!");
1556 /// # #[allow(unused_assignments)]
1558 /// let mut foo = Foo;
1562 #[lang = "rem_assign"]
1563 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1564 #[rustc_on_unimplemented = "no implementation for `{Self} %= {Rhs}`"]
1565 pub trait RemAssign<Rhs=Self> {
1566 /// The method for the `%=` operator
1567 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1568 fn rem_assign(&mut self, rhs: Rhs);
1571 macro_rules! rem_assign_impl {
1573 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1574 impl RemAssign for $t {
1576 fn rem_assign(&mut self, other: $t) { *self %= other }
1581 rem_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
1583 /// The bitwise AND assignment operator `&=`.
1587 /// In this example, the `&=` operator is lifted to a trivial `Scalar` type.
1590 /// use std::ops::BitAndAssign;
1592 /// #[derive(Debug, PartialEq)]
1593 /// struct Scalar(bool);
1595 /// impl BitAndAssign for Scalar {
1596 /// // rhs is the "right-hand side" of the expression `a &= b`
1597 /// fn bitand_assign(&mut self, rhs: Self) {
1598 /// *self = Scalar(self.0 & rhs.0)
1603 /// let mut scalar = Scalar(true);
1604 /// scalar &= Scalar(true);
1605 /// assert_eq!(scalar, Scalar(true));
1607 /// let mut scalar = Scalar(true);
1608 /// scalar &= Scalar(false);
1609 /// assert_eq!(scalar, Scalar(false));
1611 /// let mut scalar = Scalar(false);
1612 /// scalar &= Scalar(true);
1613 /// assert_eq!(scalar, Scalar(false));
1615 /// let mut scalar = Scalar(false);
1616 /// scalar &= Scalar(false);
1617 /// assert_eq!(scalar, Scalar(false));
1621 /// In this example, the `BitAndAssign` trait is implemented for a
1622 /// `BooleanVector` struct.
1625 /// use std::ops::BitAndAssign;
1627 /// #[derive(Debug, PartialEq)]
1628 /// struct BooleanVector(Vec<bool>);
1630 /// impl BitAndAssign for BooleanVector {
1631 /// // rhs is the "right-hand side" of the expression `a &= b`
1632 /// fn bitand_assign(&mut self, rhs: Self) {
1633 /// assert_eq!(self.0.len(), rhs.0.len());
1634 /// *self = BooleanVector(self.0
1636 /// .zip(rhs.0.iter())
1637 /// .map(|(x, y)| *x && *y)
1643 /// let mut bv = BooleanVector(vec![true, true, false, false]);
1644 /// bv &= BooleanVector(vec![true, false, true, false]);
1645 /// let expected = BooleanVector(vec![true, false, false, false]);
1646 /// assert_eq!(bv, expected);
1649 #[lang = "bitand_assign"]
1650 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1651 #[rustc_on_unimplemented = "no implementation for `{Self} &= {Rhs}`"]
1652 pub trait BitAndAssign<Rhs=Self> {
1653 /// The method for the `&=` operator
1654 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1655 fn bitand_assign(&mut self, rhs: Rhs);
1658 macro_rules! bitand_assign_impl {
1660 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1661 impl BitAndAssign for $t {
1663 fn bitand_assign(&mut self, other: $t) { *self &= other }
1668 bitand_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1670 /// The bitwise OR assignment operator `|=`.
1674 /// A trivial implementation of `BitOrAssign`. When `Foo |= Foo` happens, it ends up
1675 /// calling `bitor_assign`, and therefore, `main` prints `Bitwise Or-ing!`.
1678 /// use std::ops::BitOrAssign;
1682 /// impl BitOrAssign for Foo {
1683 /// fn bitor_assign(&mut self, _rhs: Foo) {
1684 /// println!("Bitwise Or-ing!");
1688 /// # #[allow(unused_assignments)]
1690 /// let mut foo = Foo;
1694 #[lang = "bitor_assign"]
1695 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1696 #[rustc_on_unimplemented = "no implementation for `{Self} |= {Rhs}`"]
1697 pub trait BitOrAssign<Rhs=Self> {
1698 /// The method for the `|=` operator
1699 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1700 fn bitor_assign(&mut self, rhs: Rhs);
1703 macro_rules! bitor_assign_impl {
1705 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1706 impl BitOrAssign for $t {
1708 fn bitor_assign(&mut self, other: $t) { *self |= other }
1713 bitor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1715 /// The bitwise XOR assignment operator `^=`.
1719 /// A trivial implementation of `BitXorAssign`. When `Foo ^= Foo` happens, it ends up
1720 /// calling `bitxor_assign`, and therefore, `main` prints `Bitwise Xor-ing!`.
1723 /// use std::ops::BitXorAssign;
1727 /// impl BitXorAssign for Foo {
1728 /// fn bitxor_assign(&mut self, _rhs: Foo) {
1729 /// println!("Bitwise Xor-ing!");
1733 /// # #[allow(unused_assignments)]
1735 /// let mut foo = Foo;
1739 #[lang = "bitxor_assign"]
1740 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1741 #[rustc_on_unimplemented = "no implementation for `{Self} ^= {Rhs}`"]
1742 pub trait BitXorAssign<Rhs=Self> {
1743 /// The method for the `^=` operator
1744 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1745 fn bitxor_assign(&mut self, rhs: Rhs);
1748 macro_rules! bitxor_assign_impl {
1750 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1751 impl BitXorAssign for $t {
1753 fn bitxor_assign(&mut self, other: $t) { *self ^= other }
1758 bitxor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1760 /// The left shift assignment operator `<<=`.
1764 /// A trivial implementation of `ShlAssign`. When `Foo <<= Foo` happens, it ends up
1765 /// calling `shl_assign`, and therefore, `main` prints `Shifting left!`.
1768 /// use std::ops::ShlAssign;
1772 /// impl ShlAssign<Foo> for Foo {
1773 /// fn shl_assign(&mut self, _rhs: Foo) {
1774 /// println!("Shifting left!");
1778 /// # #[allow(unused_assignments)]
1780 /// let mut foo = Foo;
1784 #[lang = "shl_assign"]
1785 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1786 #[rustc_on_unimplemented = "no implementation for `{Self} <<= {Rhs}`"]
1787 pub trait ShlAssign<Rhs> {
1788 /// The method for the `<<=` operator
1789 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1790 fn shl_assign(&mut self, rhs: Rhs);
1793 macro_rules! shl_assign_impl {
1795 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1796 impl ShlAssign<$f> for $t {
1798 #[rustc_inherit_overflow_checks]
1799 fn shl_assign(&mut self, other: $f) {
1806 macro_rules! shl_assign_impl_all {
1808 shl_assign_impl! { $t, u8 }
1809 shl_assign_impl! { $t, u16 }
1810 shl_assign_impl! { $t, u32 }
1811 shl_assign_impl! { $t, u64 }
1812 shl_assign_impl! { $t, u128 }
1813 shl_assign_impl! { $t, usize }
1815 shl_assign_impl! { $t, i8 }
1816 shl_assign_impl! { $t, i16 }
1817 shl_assign_impl! { $t, i32 }
1818 shl_assign_impl! { $t, i64 }
1819 shl_assign_impl! { $t, i128 }
1820 shl_assign_impl! { $t, isize }
1824 shl_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1826 /// The right shift assignment operator `>>=`.
1830 /// A trivial implementation of `ShrAssign`. When `Foo >>= Foo` happens, it ends up
1831 /// calling `shr_assign`, and therefore, `main` prints `Shifting right!`.
1834 /// use std::ops::ShrAssign;
1838 /// impl ShrAssign<Foo> for Foo {
1839 /// fn shr_assign(&mut self, _rhs: Foo) {
1840 /// println!("Shifting right!");
1844 /// # #[allow(unused_assignments)]
1846 /// let mut foo = Foo;
1850 #[lang = "shr_assign"]
1851 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1852 #[rustc_on_unimplemented = "no implementation for `{Self} >>= {Rhs}`"]
1853 pub trait ShrAssign<Rhs=Self> {
1854 /// The method for the `>>=` operator
1855 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1856 fn shr_assign(&mut self, rhs: Rhs);
1859 macro_rules! shr_assign_impl {
1861 #[stable(feature = "op_assign_traits", since = "1.8.0")]
1862 impl ShrAssign<$f> for $t {
1864 #[rustc_inherit_overflow_checks]
1865 fn shr_assign(&mut self, other: $f) {
1872 macro_rules! shr_assign_impl_all {
1874 shr_assign_impl! { $t, u8 }
1875 shr_assign_impl! { $t, u16 }
1876 shr_assign_impl! { $t, u32 }
1877 shr_assign_impl! { $t, u64 }
1878 shr_assign_impl! { $t, u128 }
1879 shr_assign_impl! { $t, usize }
1881 shr_assign_impl! { $t, i8 }
1882 shr_assign_impl! { $t, i16 }
1883 shr_assign_impl! { $t, i32 }
1884 shr_assign_impl! { $t, i64 }
1885 shr_assign_impl! { $t, i128 }
1886 shr_assign_impl! { $t, isize }
1890 shr_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
1892 /// The `Index` trait is used to specify the functionality of indexing operations
1893 /// like `container[index]` when used in an immutable context.
1895 /// `container[index]` is actually syntactic sugar for `*container.index(index)`,
1896 /// but only when used as an immutable value. If a mutable value is requested,
1897 /// [`IndexMut`] is used instead. This allows nice things such as
1898 /// `let value = v[index]` if `value` implements [`Copy`].
1900 /// [`IndexMut`]: ../../std/ops/trait.IndexMut.html
1901 /// [`Copy`]: ../../std/marker/trait.Copy.html
1905 /// The following example implements `Index` on a read-only `NucleotideCount`
1906 /// container, enabling individual counts to be retrieved with index syntax.
1909 /// use std::ops::Index;
1911 /// enum Nucleotide {
1918 /// struct NucleotideCount {
1925 /// impl Index<Nucleotide> for NucleotideCount {
1926 /// type Output = usize;
1928 /// fn index(&self, nucleotide: Nucleotide) -> &usize {
1929 /// match nucleotide {
1930 /// Nucleotide::A => &self.a,
1931 /// Nucleotide::C => &self.c,
1932 /// Nucleotide::G => &self.g,
1933 /// Nucleotide::T => &self.t,
1938 /// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
1939 /// assert_eq!(nucleotide_count[Nucleotide::A], 14);
1940 /// assert_eq!(nucleotide_count[Nucleotide::C], 9);
1941 /// assert_eq!(nucleotide_count[Nucleotide::G], 10);
1942 /// assert_eq!(nucleotide_count[Nucleotide::T], 12);
1945 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 pub trait Index<Idx: ?Sized> {
1948 /// The returned type after indexing
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 type Output: ?Sized;
1952 /// The method for the indexing (`container[index]`) operation
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 fn index(&self, index: Idx) -> &Self::Output;
1957 /// The `IndexMut` trait is used to specify the functionality of indexing
1958 /// operations like `container[index]` when used in a mutable context.
1960 /// `container[index]` is actually syntactic sugar for
1961 /// `*container.index_mut(index)`, but only when used as a mutable value. If
1962 /// an immutable value is requested, the [`Index`] trait is used instead. This
1963 /// allows nice things such as `v[index] = value` if `value` implements [`Copy`].
1965 /// [`Index`]: ../../std/ops/trait.Index.html
1966 /// [`Copy`]: ../../std/marker/trait.Copy.html
1970 /// A very simple implementation of a `Balance` struct that has two sides, where
1971 /// each can be indexed mutably and immutably.
1974 /// use std::ops::{Index,IndexMut};
1976 /// #[derive(Debug)]
1982 /// #[derive(Debug, PartialEq)]
1988 /// struct Balance {
1989 /// pub left: Weight,
1990 /// pub right:Weight,
1993 /// impl Index<Side> for Balance {
1994 /// type Output = Weight;
1996 /// fn index<'a>(&'a self, index: Side) -> &'a Weight {
1997 /// println!("Accessing {:?}-side of balance immutably", index);
1999 /// Side::Left => &self.left,
2000 /// Side::Right => &self.right,
2005 /// impl IndexMut<Side> for Balance {
2006 /// fn index_mut<'a>(&'a mut self, index: Side) -> &'a mut Weight {
2007 /// println!("Accessing {:?}-side of balance mutably", index);
2009 /// Side::Left => &mut self.left,
2010 /// Side::Right => &mut self.right,
2016 /// let mut balance = Balance {
2017 /// right: Weight::Kilogram(2.5),
2018 /// left: Weight::Pound(1.5),
2021 /// // In this case balance[Side::Right] is sugar for
2022 /// // *balance.index(Side::Right), since we are only reading
2023 /// // balance[Side::Right], not writing it.
2024 /// assert_eq!(balance[Side::Right],Weight::Kilogram(2.5));
2026 /// // However in this case balance[Side::Left] is sugar for
2027 /// // *balance.index_mut(Side::Left), since we are writing
2028 /// // balance[Side::Left].
2029 /// balance[Side::Left] = Weight::Kilogram(3.0);
2032 #[lang = "index_mut"]
2033 #[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
2036 /// The method for the mutable indexing (`container[index]`) operation
2037 #[stable(feature = "rust1", since = "1.0.0")]
2038 fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
2041 /// An unbounded range. Use `..` (two dots) for its shorthand.
2043 /// Its primary use case is slicing index. It cannot serve as an iterator
2044 /// because it doesn't have a starting point.
2048 /// The `..` syntax is a `RangeFull`:
2051 /// assert_eq!((..), std::ops::RangeFull);
2054 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2055 /// `for` loop directly. This won't compile:
2063 /// Used as a slicing index, `RangeFull` produces the full array as a slice.
2066 /// let arr = [0, 1, 2, 3];
2067 /// assert_eq!(arr[ .. ], [0,1,2,3]); // RangeFull
2068 /// assert_eq!(arr[ ..3], [0,1,2 ]);
2069 /// assert_eq!(arr[1.. ], [ 1,2,3]);
2070 /// assert_eq!(arr[1..3], [ 1,2 ]);
2072 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 pub struct RangeFull;
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl fmt::Debug for RangeFull {
2078 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2083 /// A (half-open) range which is bounded at both ends: { x | start <= x < end }.
2084 /// Use `start..end` (two dots) for its shorthand.
2086 /// See the [`contains`](#method.contains) method for its characterization.
2092 /// assert_eq!((3..5), std::ops::Range{ start: 3, end: 5 });
2093 /// assert_eq!(3+4+5, (3..6).sum());
2095 /// let arr = [0, 1, 2, 3];
2096 /// assert_eq!(arr[ .. ], [0,1,2,3]);
2097 /// assert_eq!(arr[ ..3], [0,1,2 ]);
2098 /// assert_eq!(arr[1.. ], [ 1,2,3]);
2099 /// assert_eq!(arr[1..3], [ 1,2 ]); // Range
2102 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
2103 #[stable(feature = "rust1", since = "1.0.0")]
2104 pub struct Range<Idx> {
2105 /// The lower bound of the range (inclusive).
2106 #[stable(feature = "rust1", since = "1.0.0")]
2108 /// The upper bound of the range (exclusive).
2109 #[stable(feature = "rust1", since = "1.0.0")]
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
2115 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2116 write!(fmt, "{:?}..{:?}", self.start, self.end)
2120 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2121 impl<Idx: PartialOrd<Idx>> Range<Idx> {
2125 /// #![feature(range_contains)]
2127 /// assert!( ! (3..5).contains(2));
2128 /// assert!( (3..5).contains(3));
2129 /// assert!( (3..5).contains(4));
2130 /// assert!( ! (3..5).contains(5));
2132 /// assert!( ! (3..3).contains(3));
2133 /// assert!( ! (3..2).contains(3));
2136 pub fn contains(&self, item: Idx) -> bool {
2137 (self.start <= item) && (item < self.end)
2141 /// A range which is only bounded below: { x | start <= x }.
2142 /// Use `start..` for its shorthand.
2144 /// See the [`contains`](#method.contains) method for its characterization.
2146 /// Note: Currently, no overflow checking is done for the iterator
2147 /// implementation; if you use an integer range and the integer overflows, it
2148 /// might panic in debug mode or create an endless loop in release mode. This
2149 /// overflow behavior might change in the future.
2155 /// assert_eq!((2..), std::ops::RangeFrom{ start: 2 });
2156 /// assert_eq!(2+3+4, (2..).take(3).sum());
2158 /// let arr = [0, 1, 2, 3];
2159 /// assert_eq!(arr[ .. ], [0,1,2,3]);
2160 /// assert_eq!(arr[ ..3], [0,1,2 ]);
2161 /// assert_eq!(arr[1.. ], [ 1,2,3]); // RangeFrom
2162 /// assert_eq!(arr[1..3], [ 1,2 ]);
2165 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
2166 #[stable(feature = "rust1", since = "1.0.0")]
2167 pub struct RangeFrom<Idx> {
2168 /// The lower bound of the range (inclusive).
2169 #[stable(feature = "rust1", since = "1.0.0")]
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
2175 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2176 write!(fmt, "{:?}..", self.start)
2180 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2181 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
2185 /// #![feature(range_contains)]
2187 /// assert!( ! (3..).contains(2));
2188 /// assert!( (3..).contains(3));
2189 /// assert!( (3..).contains(1_000_000_000));
2192 pub fn contains(&self, item: Idx) -> bool {
2193 (self.start <= item)
2197 /// A range which is only bounded above: { x | x < end }.
2198 /// Use `..end` (two dots) for its shorthand.
2200 /// See the [`contains`](#method.contains) method for its characterization.
2202 /// It cannot serve as an iterator because it doesn't have a starting point.
2206 /// The `..{integer}` syntax is a `RangeTo`:
2209 /// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
2212 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2213 /// `for` loop directly. This won't compile:
2221 /// When used as a slicing index, `RangeTo` produces a slice of all array
2222 /// elements before the index indicated by `end`.
2225 /// let arr = [0, 1, 2, 3];
2226 /// assert_eq!(arr[ .. ], [0,1,2,3]);
2227 /// assert_eq!(arr[ ..3], [0,1,2 ]); // RangeTo
2228 /// assert_eq!(arr[1.. ], [ 1,2,3]);
2229 /// assert_eq!(arr[1..3], [ 1,2 ]);
2231 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2232 #[stable(feature = "rust1", since = "1.0.0")]
2233 pub struct RangeTo<Idx> {
2234 /// The upper bound of the range (exclusive).
2235 #[stable(feature = "rust1", since = "1.0.0")]
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
2241 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2242 write!(fmt, "..{:?}", self.end)
2246 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2247 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
2251 /// #![feature(range_contains)]
2253 /// assert!( (..5).contains(-1_000_000_000));
2254 /// assert!( (..5).contains(4));
2255 /// assert!( ! (..5).contains(5));
2258 pub fn contains(&self, item: Idx) -> bool {
2263 /// An inclusive range which is bounded at both ends: { x | start <= x <= end }.
2264 /// Use `start...end` (three dots) for its shorthand.
2266 /// See the [`contains`](#method.contains) method for its characterization.
2271 /// #![feature(inclusive_range,inclusive_range_syntax)]
2273 /// assert_eq!((3...5), std::ops::RangeInclusive::NonEmpty{ start: 3, end: 5 });
2274 /// assert_eq!(3+4+5, (3...5).sum());
2276 /// let arr = [0, 1, 2, 3];
2277 /// assert_eq!(arr[ ...2], [0,1,2 ]);
2278 /// assert_eq!(arr[1...2], [ 1,2 ]); // RangeInclusive
2281 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
2282 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2283 pub enum RangeInclusive<Idx> {
2284 /// Empty range (iteration has finished)
2285 #[unstable(feature = "inclusive_range",
2286 reason = "recently added, follows RFC",
2289 /// The point at which iteration finished
2290 #[unstable(feature = "inclusive_range",
2291 reason = "recently added, follows RFC",
2295 /// Non-empty range (iteration will yield value(s))
2296 #[unstable(feature = "inclusive_range",
2297 reason = "recently added, follows RFC",
2300 /// The lower bound of the range (inclusive).
2301 #[unstable(feature = "inclusive_range",
2302 reason = "recently added, follows RFC",
2305 /// The upper bound of the range (inclusive).
2306 #[unstable(feature = "inclusive_range",
2307 reason = "recently added, follows RFC",
2313 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2314 impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
2315 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2316 use self::RangeInclusive::*;
2319 Empty { ref at } => write!(fmt, "[empty range @ {:?}]", at),
2320 NonEmpty { ref start, ref end } => write!(fmt, "{:?}...{:?}", start, end),
2325 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2326 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
2330 /// #![feature(range_contains,inclusive_range_syntax)]
2332 /// assert!( ! (3...5).contains(2));
2333 /// assert!( (3...5).contains(3));
2334 /// assert!( (3...5).contains(4));
2335 /// assert!( (3...5).contains(5));
2336 /// assert!( ! (3...5).contains(6));
2338 /// assert!( (3...3).contains(3));
2339 /// assert!( ! (3...2).contains(3));
2342 pub fn contains(&self, item: Idx) -> bool {
2343 if let &RangeInclusive::NonEmpty{ref start, ref end} = self {
2344 (*start <= item) && (item <= *end)
2349 /// An inclusive range which is only bounded above: { x | x <= end }.
2350 /// Use `...end` (three dots) for its shorthand.
2352 /// See the [`contains`](#method.contains) method for its characterization.
2354 /// It cannot serve as an iterator because it doesn't have a starting point.
2358 /// The `...{integer}` syntax is a `RangeToInclusive`:
2361 /// #![feature(inclusive_range,inclusive_range_syntax)]
2362 /// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
2365 /// It does not have an `IntoIterator` implementation, so you can't use it in a
2366 /// `for` loop directly. This won't compile:
2374 /// When used as a slicing index, `RangeToInclusive` produces a slice of all
2375 /// array elements up to and including the index indicated by `end`.
2378 /// #![feature(inclusive_range_syntax)]
2379 /// let arr = [0, 1, 2, 3];
2380 /// assert_eq!(arr[ ...2], [0,1,2 ]); // RangeToInclusive
2381 /// assert_eq!(arr[1...2], [ 1,2 ]);
2383 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2384 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2385 pub struct RangeToInclusive<Idx> {
2386 /// The upper bound of the range (inclusive)
2387 #[unstable(feature = "inclusive_range",
2388 reason = "recently added, follows RFC",
2393 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
2394 impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
2395 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2396 write!(fmt, "...{:?}", self.end)
2400 #[unstable(feature = "range_contains", reason = "recently added as per RFC", issue = "32311")]
2401 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
2405 /// #![feature(range_contains,inclusive_range_syntax)]
2407 /// assert!( (...5).contains(-1_000_000_000));
2408 /// assert!( (...5).contains(5));
2409 /// assert!( ! (...5).contains(6));
2412 pub fn contains(&self, item: Idx) -> bool {
2417 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
2418 // because underflow would be possible with (..0).into()
2420 /// The `Deref` trait is used to specify the functionality of dereferencing
2421 /// operations, like `*v`.
2423 /// `Deref` also enables ['`Deref` coercions'][coercions].
2425 /// [coercions]: ../../book/deref-coercions.html
2429 /// A struct with a single field which is accessible via dereferencing the
2433 /// use std::ops::Deref;
2435 /// struct DerefExample<T> {
2439 /// impl<T> Deref for DerefExample<T> {
2440 /// type Target = T;
2442 /// fn deref(&self) -> &T {
2448 /// let x = DerefExample { value: 'a' };
2449 /// assert_eq!('a', *x);
2453 #[stable(feature = "rust1", since = "1.0.0")]
2455 /// The resulting type after dereferencing
2456 #[stable(feature = "rust1", since = "1.0.0")]
2457 type Target: ?Sized;
2459 /// The method called to dereference a value
2460 #[stable(feature = "rust1", since = "1.0.0")]
2461 fn deref(&self) -> &Self::Target;
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 impl<'a, T: ?Sized> Deref for &'a T {
2468 fn deref(&self) -> &T { *self }
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 impl<'a, T: ?Sized> Deref for &'a mut T {
2475 fn deref(&self) -> &T { *self }
2478 /// The `DerefMut` trait is used to specify the functionality of dereferencing
2479 /// mutably like `*v = 1;`
2481 /// `DerefMut` also enables ['`Deref` coercions'][coercions].
2483 /// [coercions]: ../../book/deref-coercions.html
2487 /// A struct with a single field which is modifiable via dereferencing the
2491 /// use std::ops::{Deref, DerefMut};
2493 /// struct DerefMutExample<T> {
2497 /// impl<T> Deref for DerefMutExample<T> {
2498 /// type Target = T;
2500 /// fn deref(&self) -> &T {
2505 /// impl<T> DerefMut for DerefMutExample<T> {
2506 /// fn deref_mut(&mut self) -> &mut T {
2512 /// let mut x = DerefMutExample { value: 'a' };
2514 /// assert_eq!('b', *x);
2517 #[lang = "deref_mut"]
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 pub trait DerefMut: Deref {
2520 /// The method called to mutably dereference a value
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 fn deref_mut(&mut self) -> &mut Self::Target;
2525 #[stable(feature = "rust1", since = "1.0.0")]
2526 impl<'a, T: ?Sized> DerefMut for &'a mut T {
2527 fn deref_mut(&mut self) -> &mut T { *self }
2530 /// A version of the call operator that takes an immutable receiver.
2534 /// Closures automatically implement this trait, which allows them to be
2535 /// invoked. Note, however, that `Fn` takes an immutable reference to any
2536 /// captured variables. To take a mutable capture, implement [`FnMut`], and to
2537 /// consume the capture, implement [`FnOnce`].
2539 /// [`FnMut`]: trait.FnMut.html
2540 /// [`FnOnce`]: trait.FnOnce.html
2543 /// let square = |x| x * x;
2544 /// assert_eq!(square(5), 25);
2547 /// Closures can also be passed to higher-level functions through a `Fn`
2548 /// parameter (or a `FnMut` or `FnOnce` parameter, which are supertraits of
2552 /// fn call_with_one<F>(func: F) -> usize
2553 /// where F: Fn(usize) -> usize {
2557 /// let double = |x| x * 2;
2558 /// assert_eq!(call_with_one(double), 2);
2561 #[stable(feature = "rust1", since = "1.0.0")]
2562 #[rustc_paren_sugar]
2563 #[fundamental] // so that regex can rely that `&str: !FnMut`
2564 pub trait Fn<Args> : FnMut<Args> {
2565 /// This is called when the call operator is used.
2566 #[unstable(feature = "fn_traits", issue = "29625")]
2567 extern "rust-call" fn call(&self, args: Args) -> Self::Output;
2570 /// A version of the call operator that takes a mutable receiver.
2574 /// Closures that mutably capture variables automatically implement this trait,
2575 /// which allows them to be invoked.
2580 /// let mut square_x = || x *= x;
2583 /// assert_eq!(x, 25);
2586 /// Closures can also be passed to higher-level functions through a `FnMut`
2587 /// parameter (or a `FnOnce` parameter, which is a supertrait of `FnMut`).
2590 /// fn do_twice<F>(mut func: F)
2591 /// where F: FnMut()
2597 /// let mut x: usize = 1;
2599 /// let add_two_to_x = || x += 2;
2600 /// do_twice(add_two_to_x);
2603 /// assert_eq!(x, 5);
2606 #[stable(feature = "rust1", since = "1.0.0")]
2607 #[rustc_paren_sugar]
2608 #[fundamental] // so that regex can rely that `&str: !FnMut`
2609 pub trait FnMut<Args> : FnOnce<Args> {
2610 /// This is called when the call operator is used.
2611 #[unstable(feature = "fn_traits", issue = "29625")]
2612 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
2615 /// A version of the call operator that takes a by-value receiver.
2619 /// By-value closures automatically implement this trait, which allows them to
2624 /// let square_x = move || x * x;
2625 /// assert_eq!(square_x(), 25);
2628 /// By-value Closures can also be passed to higher-level functions through a
2629 /// `FnOnce` parameter.
2632 /// fn consume_with_relish<F>(func: F)
2633 /// where F: FnOnce() -> String
2635 /// // `func` consumes its captured variables, so it cannot be run more
2637 /// println!("Consumed: {}", func());
2639 /// println!("Delicious!");
2641 /// // Attempting to invoke `func()` again will throw a `use of moved
2642 /// // value` error for `func`
2645 /// let x = String::from("x");
2646 /// let consume_and_return_x = move || x;
2647 /// consume_with_relish(consume_and_return_x);
2649 /// // `consume_and_return_x` can no longer be invoked at this point
2652 #[stable(feature = "rust1", since = "1.0.0")]
2653 #[rustc_paren_sugar]
2654 #[fundamental] // so that regex can rely that `&str: !FnMut`
2655 pub trait FnOnce<Args> {
2656 /// The returned type after the call operator is used.
2657 #[stable(feature = "fn_once_output", since = "1.12.0")]
2660 /// This is called when the call operator is used.
2661 #[unstable(feature = "fn_traits", issue = "29625")]
2662 extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
2666 #[stable(feature = "rust1", since = "1.0.0")]
2667 impl<'a,A,F:?Sized> Fn<A> for &'a F
2670 extern "rust-call" fn call(&self, args: A) -> F::Output {
2675 #[stable(feature = "rust1", since = "1.0.0")]
2676 impl<'a,A,F:?Sized> FnMut<A> for &'a F
2679 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2684 #[stable(feature = "rust1", since = "1.0.0")]
2685 impl<'a,A,F:?Sized> FnOnce<A> for &'a F
2688 type Output = F::Output;
2690 extern "rust-call" fn call_once(self, args: A) -> F::Output {
2695 #[stable(feature = "rust1", since = "1.0.0")]
2696 impl<'a,A,F:?Sized> FnMut<A> for &'a mut F
2699 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
2700 (*self).call_mut(args)
2704 #[stable(feature = "rust1", since = "1.0.0")]
2705 impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F
2708 type Output = F::Output;
2709 extern "rust-call" fn call_once(mut self, args: A) -> F::Output {
2710 (*self).call_mut(args)
2715 /// Trait that indicates that this is a pointer or a wrapper for one,
2716 /// where unsizing can be performed on the pointee.
2718 /// See the [DST coercion RfC][dst-coerce] and [the nomicon entry on coercion][nomicon-coerce]
2719 /// for more details.
2721 /// For builtin pointer types, pointers to `T` will coerce to pointers to `U` if `T: Unsize<U>`
2722 /// by converting from a thin pointer to a fat pointer.
2724 /// For custom types, the coercion here works by coercing `Foo<T>` to `Foo<U>`
2725 /// provided an impl of `CoerceUnsized<Foo<U>> for Foo<T>` exists.
2726 /// Such an impl can only be written if `Foo<T>` has only a single non-phantomdata
2727 /// field involving `T`. If the type of that field is `Bar<T>`, an implementation
2728 /// of `CoerceUnsized<Bar<U>> for Bar<T>` must exist. The coercion will work by
2729 /// by coercing the `Bar<T>` field into `Bar<U>` and filling in the rest of the fields
2730 /// from `Foo<T>` to create a `Foo<U>`. This will effectively drill down to a pointer
2731 /// field and coerce that.
2733 /// Generally, for smart pointers you will implement
2734 /// `CoerceUnsized<Ptr<U>> for Ptr<T> where T: Unsize<U>, U: ?Sized`, with an
2735 /// optional `?Sized` bound on `T` itself. For wrapper types that directly embed `T`
2736 /// like `Cell<T>` and `RefCell<T>`, you
2737 /// can directly implement `CoerceUnsized<Wrap<U>> for Wrap<T> where T: CoerceUnsized<U>`.
2738 /// This will let coercions of types like `Cell<Box<T>>` work.
2740 /// [`Unsize`][unsize] is used to mark types which can be coerced to DSTs if behind
2741 /// pointers. It is implemented automatically by the compiler.
2743 /// [dst-coerce]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2744 /// [unsize]: ../marker/trait.Unsize.html
2745 /// [nomicon-coerce]: ../../nomicon/coercions.html
2746 #[unstable(feature = "coerce_unsized", issue = "27732")]
2747 #[lang="coerce_unsized"]
2748 pub trait CoerceUnsized<T> {
2753 #[unstable(feature = "coerce_unsized", issue = "27732")]
2754 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a mut U> for &'a mut T {}
2756 #[unstable(feature = "coerce_unsized", issue = "27732")]
2757 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b mut T {}
2759 #[unstable(feature = "coerce_unsized", issue = "27732")]
2760 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for &'a mut T {}
2761 // &mut T -> *const U
2762 #[unstable(feature = "coerce_unsized", issue = "27732")]
2763 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a mut T {}
2766 #[unstable(feature = "coerce_unsized", issue = "27732")]
2767 impl<'a, 'b: 'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
2769 #[unstable(feature = "coerce_unsized", issue = "27732")]
2770 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for &'a T {}
2773 #[unstable(feature = "coerce_unsized", issue = "27732")]
2774 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for *mut T {}
2775 // *mut T -> *const U
2776 #[unstable(feature = "coerce_unsized", issue = "27732")]
2777 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *mut T {}
2779 // *const T -> *const U
2780 #[unstable(feature = "coerce_unsized", issue = "27732")]
2781 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *const T {}
2783 /// Both `PLACE <- EXPR` and `box EXPR` desugar into expressions
2784 /// that allocate an intermediate "place" that holds uninitialized
2785 /// state. The desugaring evaluates EXPR, and writes the result at
2786 /// the address returned by the `pointer` method of this trait.
2788 /// A `Place` can be thought of as a special representation for a
2789 /// hypothetical `&uninit` reference (which Rust cannot currently
2790 /// express directly). That is, it represents a pointer to
2791 /// uninitialized storage.
2793 /// The client is responsible for two steps: First, initializing the
2794 /// payload (it can access its address via `pointer`). Second,
2795 /// converting the agent to an instance of the owning pointer, via the
2796 /// appropriate `finalize` method (see the `InPlace`.
2798 /// If evaluating EXPR fails, then it is up to the destructor for the
2799 /// implementation of Place to clean up any intermediate state
2800 /// (e.g. deallocate box storage, pop a stack, etc).
2801 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2802 pub trait Place<Data: ?Sized> {
2803 /// Returns the address where the input value will be written.
2804 /// Note that the data at this address is generally uninitialized,
2805 /// and thus one should use `ptr::write` for initializing it.
2806 fn pointer(&mut self) -> *mut Data;
2809 /// Interface to implementations of `PLACE <- EXPR`.
2811 /// `PLACE <- EXPR` effectively desugars into:
2815 /// let mut place = Placer::make_place(p);
2816 /// let raw_place = Place::pointer(&mut place);
2817 /// let value = EXPR;
2819 /// std::ptr::write(raw_place, value);
2820 /// InPlace::finalize(place)
2824 /// The type of `PLACE <- EXPR` is derived from the type of `PLACE`;
2825 /// if the type of `PLACE` is `P`, then the final type of the whole
2826 /// expression is `P::Place::Owner` (see the `InPlace` and `Boxed`
2829 /// Values for types implementing this trait usually are transient
2830 /// intermediate values (e.g. the return value of `Vec::emplace_back`)
2831 /// or `Copy`, since the `make_place` method takes `self` by value.
2832 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2833 pub trait Placer<Data: ?Sized> {
2834 /// `Place` is the intermedate agent guarding the
2835 /// uninitialized state for `Data`.
2836 type Place: InPlace<Data>;
2838 /// Creates a fresh place from `self`.
2839 fn make_place(self) -> Self::Place;
2842 /// Specialization of `Place` trait supporting `PLACE <- EXPR`.
2843 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2844 pub trait InPlace<Data: ?Sized>: Place<Data> {
2845 /// `Owner` is the type of the end value of `PLACE <- EXPR`
2847 /// Note that when `PLACE <- EXPR` is solely used for
2848 /// side-effecting an existing data-structure,
2849 /// e.g. `Vec::emplace_back`, then `Owner` need not carry any
2850 /// information at all (e.g. it can be the unit type `()` in that
2854 /// Converts self into the final value, shifting
2855 /// deallocation/cleanup responsibilities (if any remain), over to
2856 /// the returned instance of `Owner` and forgetting self.
2857 unsafe fn finalize(self) -> Self::Owner;
2860 /// Core trait for the `box EXPR` form.
2862 /// `box EXPR` effectively desugars into:
2865 /// let mut place = BoxPlace::make_place();
2866 /// let raw_place = Place::pointer(&mut place);
2867 /// let value = EXPR;
2869 /// ::std::ptr::write(raw_place, value);
2870 /// Boxed::finalize(place)
2874 /// The type of `box EXPR` is supplied from its surrounding
2875 /// context; in the above expansion, the result type `T` is used
2876 /// to determine which implementation of `Boxed` to use, and that
2877 /// `<T as Boxed>` in turn dictates determines which
2878 /// implementation of `BoxPlace` to use, namely:
2879 /// `<<T as Boxed>::Place as BoxPlace>`.
2880 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2882 /// The kind of data that is stored in this kind of box.
2883 type Data; /* (`Data` unused b/c cannot yet express below bound.) */
2884 /// The place that will negotiate the storage of the data.
2885 type Place: BoxPlace<Self::Data>;
2887 /// Converts filled place into final owning value, shifting
2888 /// deallocation/cleanup responsibilities (if any remain), over to
2889 /// returned instance of `Self` and forgetting `filled`.
2890 unsafe fn finalize(filled: Self::Place) -> Self;
2893 /// Specialization of `Place` trait supporting `box EXPR`.
2894 #[unstable(feature = "placement_new_protocol", issue = "27779")]
2895 pub trait BoxPlace<Data: ?Sized> : Place<Data> {
2896 /// Creates a globally fresh place.
2897 fn make_place() -> Self;
2900 /// A trait for types which have success and error states and are meant to work
2901 /// with the question mark operator.
2902 /// When the `?` operator is used with a value, whether the value is in the
2903 /// success or error state is determined by calling `translate`.
2905 /// This trait is **very** experimental, it will probably be iterated on heavily
2906 /// before it is stabilised. Implementors should expect change. Users of `?`
2907 /// should not rely on any implementations of `Carrier` other than `Result`,
2908 /// i.e., you should not expect `?` to continue to work with `Option`, etc.
2909 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2911 /// The type of the value when computation succeeds.
2913 /// The type of the value when computation errors out.
2916 /// Create a `Carrier` from a success value.
2917 fn from_success(_: Self::Success) -> Self;
2919 /// Create a `Carrier` from an error value.
2920 fn from_error(_: Self::Error) -> Self;
2922 /// Translate this `Carrier` to another implementation of `Carrier` with the
2923 /// same associated types.
2924 fn translate<T>(self) -> T where T: Carrier<Success=Self::Success, Error=Self::Error>;
2927 #[unstable(feature = "question_mark_carrier", issue = "31436")]
2928 impl<U, V> Carrier for Result<U, V> {
2932 fn from_success(u: U) -> Result<U, V> {
2936 fn from_error(e: V) -> Result<U, V> {
2940 fn translate<T>(self) -> T
2941 where T: Carrier<Success=U, Error=V>
2944 Ok(u) => T::from_success(u),
2945 Err(e) => T::from_error(e),
2950 struct _DummyErrorType;
2952 impl Carrier for _DummyErrorType {
2956 fn from_success(_: ()) -> _DummyErrorType {
2960 fn from_error(_: ()) -> _DummyErrorType {
2964 fn translate<T>(self) -> T
2965 where T: Carrier<Success=(), Error=()>