]> git.lizzy.rs Git - rust.git/commitdiff
Rollup merge of #35863 - matthew-piziak:shl-example, r=steveklabnik
authorGuillaume Gomez <guillaume1.gomez@gmail.com>
Tue, 30 Aug 2016 08:39:06 +0000 (10:39 +0200)
committerGitHub <noreply@github.com>
Tue, 30 Aug 2016 08:39:06 +0000 (10:39 +0200)
add evocative examples for `Shl` and `Shr`

r? @steveklabnik

1  2 
src/libcore/ops.rs

diff --combined src/libcore/ops.rs
index d833da5a0d230fabe576d3dc579a2a7eb6178a7a,3bf76539356611ee061e8a14cef163ca0e171907..ae8f192e3451964b127bc35c58fe0fb9da8feaa0
  //! ```
  //!
  //! See the documentation for each trait for an example implementation.
 +//!
 +//! The [`Fn`], [`FnMut`], and [`FnOnce`] traits are implemented by types that can be
 +//! invoked like functions. Note that `Fn` takes `&self`, `FnMut` takes `&mut
 +//! self` and `FnOnce` takes `self`. These correspond to the three kinds of
 +//! methods that can be invoked on an instance: call-by-reference,
 +//! call-by-mutable-reference, and call-by-value. The most common use of these
 +//! traits is to act as bounds to higher-level functions that take functions or
 +//! closures as arguments.
 +//!
 +//! [`Fn`]: trait.Fn.html
 +//! [`FnMut`]: trait.FnMut.html
 +//! [`FnOnce`]: trait.FnOnce.html
 +//!
 +//! Taking a `Fn` as a parameter:
 +//!
 +//! ```rust
 +//! fn call_with_one<F>(func: F) -> usize
 +//!     where F: Fn(usize) -> usize
 +//! {
 +//!     func(1)
 +//! }
 +//!
 +//! let double = |x| x * 2;
 +//! assert_eq!(call_with_one(double), 2);
 +//! ```
 +//!
 +//! Taking a `FnMut` as a parameter:
 +//!
 +//! ```rust
 +//! fn do_twice<F>(mut func: F)
 +//!     where F: FnMut()
 +//! {
 +//!     func();
 +//!     func();
 +//! }
 +//!
 +//! let mut x: usize = 1;
 +//! {
 +//!     let add_two_to_x = || x += 2;
 +//!     do_twice(add_two_to_x);
 +//! }
 +//!
 +//! assert_eq!(x, 5);
 +//! ```
 +//!
 +//! Taking a `FnOnce` as a parameter:
 +//!
 +//! ```rust
 +//! fn consume_with_relish<F>(func: F)
 +//!     where F: FnOnce() -> String
 +//! {
 +//!     // `func` consumes its captured variables, so it cannot be run more
 +//!     // than once
 +//!     println!("Consumed: {}", func());
 +//!
 +//!     println!("Delicious!");
 +//!
 +//!     // Attempting to invoke `func()` again will throw a `use of moved
 +//!     // value` error for `func`
 +//! }
 +//!
 +//! let x = String::from("x");
 +//! let consume_and_return_x = move || x;
 +//! consume_with_relish(consume_and_return_x);
 +//!
 +//! // `consume_and_return_x` can no longer be invoked at this point
 +//! ```
  
  #![stable(feature = "rust1", since = "1.0.0")]
  
 -use cmp::PartialOrd;
  use fmt;
 -use marker::{Sized, Unsize};
 +use marker::Unsize;
  
  /// The `Drop` trait is used to run some code when a value goes out of scope.
  /// This is sometimes called a 'destructor'.
@@@ -310,38 -244,25 +310,38 @@@ add_impl! { usize u8 u16 u32 u64 isize 
  ///
  /// # Examples
  ///
 -/// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up
 -/// calling `sub`, and therefore, `main` prints `Subtracting!`.
 +/// This example creates a `Point` struct that implements the `Sub` trait, and
 +/// then demonstrates subtracting two `Point`s.
  ///
  /// ```
  /// use std::ops::Sub;
  ///
 -/// struct Foo;
 +/// #[derive(Debug)]
 +/// struct Point {
 +///     x: i32,
 +///     y: i32,
 +/// }
  ///
 -/// impl Sub for Foo {
 -///     type Output = Foo;
 +/// impl Sub for Point {
 +///     type Output = Point;
  ///
 -///     fn sub(self, _rhs: Foo) -> Foo {
 -///         println!("Subtracting!");
 -///         self
 +///     fn sub(self, other: Point) -> Point {
 +///         Point {
 +///             x: self.x - other.x,
 +///             y: self.y - other.y,
 +///         }
 +///     }
 +/// }
 +///
 +/// impl PartialEq for Point {
 +///     fn eq(&self, other: &Self) -> bool {
 +///         self.x == other.x && self.y == other.y
  ///     }
  /// }
  ///
  /// fn main() {
 -///     Foo - Foo;
 +///     assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 },
 +///                Point { x: 1, y: 0 });
  /// }
  /// ```
  #[lang = "sub"]
@@@ -377,63 -298,26 +377,63 @@@ sub_impl! { usize u8 u16 u32 u64 isize 
  ///
  /// # Examples
  ///
 -/// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up
 -/// calling `mul`, and therefore, `main` prints `Multiplying!`.
 +/// Implementing a `Mul`tipliable rational number struct:
  ///
  /// ```
  /// use std::ops::Mul;
  ///
 -/// struct Foo;
 +/// // The uniqueness of rational numbers in lowest terms is a consequence of
 +/// // the fundamental theorem of arithmetic.
 +/// #[derive(Eq)]
 +/// #[derive(PartialEq, Debug)]
 +/// struct Rational {
 +///     nominator: usize,
 +///     denominator: usize,
 +/// }
  ///
 -/// impl Mul for Foo {
 -///     type Output = Foo;
 +/// impl Rational {
 +///     fn new(nominator: usize, denominator: usize) -> Self {
 +///         if denominator == 0 {
 +///             panic!("Zero is an invalid denominator!");
 +///         }
  ///
 -///     fn mul(self, _rhs: Foo) -> Foo {
 -///         println!("Multiplying!");
 -///         self
 +///         // Reduce to lowest terms by dividing by the greatest common
 +///         // divisor.
 +///         let gcd = gcd(nominator, denominator);
 +///         Rational {
 +///             nominator: nominator / gcd,
 +///             denominator: denominator / gcd,
 +///         }
  ///     }
  /// }
  ///
 -/// fn main() {
 -///     Foo * Foo;
 +/// impl Mul for Rational {
 +///     // The multiplication of rational numbers is a closed operation.
 +///     type Output = Self;
 +///
 +///     fn mul(self, rhs: Self) -> Self {
 +///         let nominator = self.nominator * rhs.nominator;
 +///         let denominator = self.denominator * rhs.denominator;
 +///         Rational::new(nominator, denominator)
 +///     }
  /// }
 +///
 +/// // Euclid's two-thousand-year-old algorithm for finding the greatest common
 +/// // divisor.
 +/// fn gcd(x: usize, y: usize) -> usize {
 +///     let mut x = x;
 +///     let mut y = y;
 +///     while y != 0 {
 +///         let t = y;
 +///         y = x % y;
 +///         x = t;
 +///     }
 +///     x
 +/// }
 +///
 +/// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
 +/// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4),
 +///            Rational::new(1, 2));
  /// ```
  ///
  /// Note that `RHS = Self` by default, but this is not mandatory. Here is an
@@@ -499,68 -383,25 +499,68 @@@ mul_impl! { usize u8 u16 u32 u64 isize 
  ///
  /// # Examples
  ///
 -/// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up
 -/// calling `div`, and therefore, `main` prints `Dividing!`.
 +/// Implementing a `Div`idable rational number struct:
  ///
  /// ```
  /// use std::ops::Div;
  ///
 -/// struct Foo;
 +/// // The uniqueness of rational numbers in lowest terms is a consequence of
 +/// // the fundamental theorem of arithmetic.
 +/// #[derive(Eq)]
 +/// #[derive(PartialEq, Debug)]
 +/// struct Rational {
 +///     nominator: usize,
 +///     denominator: usize,
 +/// }
  ///
 -/// impl Div for Foo {
 -///     type Output = Foo;
 +/// impl Rational {
 +///     fn new(nominator: usize, denominator: usize) -> Self {
 +///         if denominator == 0 {
 +///             panic!("Zero is an invalid denominator!");
 +///         }
  ///
 -///     fn div(self, _rhs: Foo) -> Foo {
 -///         println!("Dividing!");
 -///         self
 +///         // Reduce to lowest terms by dividing by the greatest common
 +///         // divisor.
 +///         let gcd = gcd(nominator, denominator);
 +///         Rational {
 +///             nominator: nominator / gcd,
 +///             denominator: denominator / gcd,
 +///         }
 +///     }
 +/// }
 +///
 +/// impl Div for Rational {
 +///     // The division of rational numbers is a closed operation.
 +///     type Output = Self;
 +///
 +///     fn div(self, rhs: Self) -> Self {
 +///         if rhs.nominator == 0 {
 +///             panic!("Cannot divide by zero-valued `Rational`!");
 +///         }
 +///
 +///         let nominator = self.nominator * rhs.denominator;
 +///         let denominator = self.denominator * rhs.nominator;
 +///         Rational::new(nominator, denominator)
  ///     }
  /// }
  ///
 +/// // Euclid's two-thousand-year-old algorithm for finding the greatest common
 +/// // divisor.
 +/// fn gcd(x: usize, y: usize) -> usize {
 +///     let mut x = x;
 +///     let mut y = y;
 +///     while y != 0 {
 +///         let t = y;
 +///         y = x % y;
 +///         x = t;
 +///     }
 +///     x
 +/// }
 +///
  /// fn main() {
 -///     Foo / Foo;
 +///     assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
 +///     assert_eq!(Rational::new(1, 2) / Rational::new(3, 4),
 +///                Rational::new(2, 3));
  /// }
  /// ```
  ///
@@@ -644,34 -485,26 +644,34 @@@ div_impl_float! { f32 f64 
  ///
  /// # Examples
  ///
 -/// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up
 -/// calling `rem`, and therefore, `main` prints `Remainder-ing!`.
 +/// This example implements `Rem` on a `SplitSlice` object. After `Rem` is
 +/// implemented, one can use the `%` operator to find out what the remaining
 +/// elements of the slice would be after splitting it into equal slices of a
 +/// given length.
  ///
  /// ```
  /// use std::ops::Rem;
  ///
 -/// struct Foo;
 +/// #[derive(PartialEq, Debug)]
 +/// struct SplitSlice<'a, T: 'a> {
 +///     slice: &'a [T],
 +/// }
  ///
 -/// impl Rem for Foo {
 -///     type Output = Foo;
 +/// impl<'a, T> Rem<usize> for SplitSlice<'a, T> {
 +///     type Output = SplitSlice<'a, T>;
  ///
 -///     fn rem(self, _rhs: Foo) -> Foo {
 -///         println!("Remainder-ing!");
 -///         self
 +///     fn rem(self, modulus: usize) -> Self {
 +///         let len = self.slice.len();
 +///         let rem = len % modulus;
 +///         let start = len - rem;
 +///         SplitSlice {slice: &self.slice[start..]}
  ///     }
  /// }
  ///
 -/// fn main() {
 -///     Foo % Foo;
 -/// }
 +/// // If we were to divide &[0, 1, 2, 3, 4, 5, 6, 7] into slices of size 3,
 +/// // the remainder would be &[6, 7]
 +/// assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3,
 +///            SplitSlice { slice: &[6, 7] });
  /// ```
  #[lang = "rem"]
  #[stable(feature = "rust1", since = "1.0.0")]
@@@ -860,41 -693,26 +860,41 @@@ not_impl! { bool usize u8 u16 u32 u64 i
  ///
  /// # Examples
  ///
 -/// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up
 -/// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`.
 +/// In this example, the `BitAnd` trait is implemented for a `BooleanVector`
 +/// struct.
  ///
  /// ```
  /// use std::ops::BitAnd;
  ///
 -/// struct Foo;
 +/// #[derive(Debug)]
 +/// struct BooleanVector {
 +///     value: Vec<bool>,
 +/// };
  ///
 -/// impl BitAnd for Foo {
 -///     type Output = Foo;
 +/// impl BitAnd for BooleanVector {
 +///     type Output = Self;
  ///
 -///     fn bitand(self, _rhs: Foo) -> Foo {
 -///         println!("Bitwise And-ing!");
 -///         self
 +///     fn bitand(self, rhs: Self) -> Self {
 +///         BooleanVector {
 +///             value: self.value
 +///                 .iter()
 +///                 .zip(rhs.value.iter())
 +///                 .map(|(x, y)| *x && *y)
 +///                 .collect(),
 +///         }
  ///     }
  /// }
  ///
 -/// fn main() {
 -///     Foo & Foo;
 +/// impl PartialEq for BooleanVector {
 +///     fn eq(&self, other: &Self) -> bool {
 +///         self.value == other.value
 +///     }
  /// }
 +///
 +/// let bv1 = BooleanVector { value: vec![true, true, false, false] };
 +/// let bv2 = BooleanVector { value: vec![true, false, true, false] };
 +/// let expected = BooleanVector { value: vec![true, false, false, false] };
 +/// assert_eq!(bv1 & bv2, expected);
  /// ```
  #[lang = "bitand"]
  #[stable(feature = "rust1", since = "1.0.0")]
@@@ -1034,25 -852,54 +1034,54 @@@ bitxor_impl! { bool usize u8 u16 u32 u6
  ///
  /// # Examples
  ///
- /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up
- /// calling `shl`, and therefore, `main` prints `Shifting left!`.
+ /// An implementation of `Shl` that lifts the `<<` operation on integers to a
+ /// `Scalar` struct.
  ///
  /// ```
  /// use std::ops::Shl;
  ///
- /// struct Foo;
+ /// #[derive(PartialEq, Debug)]
+ /// struct Scalar(usize);
  ///
- /// impl Shl<Foo> for Foo {
- ///     type Output = Foo;
+ /// impl Shl<Scalar> for Scalar {
+ ///     type Output = Self;
  ///
- ///     fn shl(self, _rhs: Foo) -> Foo {
- ///         println!("Shifting left!");
- ///         self
+ ///     fn shl(self, Scalar(rhs): Self) -> Scalar {
+ ///         let Scalar(lhs) = self;
+ ///         Scalar(lhs << rhs)
+ ///     }
+ /// }
+ /// fn main() {
+ ///     assert_eq!(Scalar(4) << Scalar(2), Scalar(16));
+ /// }
+ /// ```
+ ///
+ /// An implementation of `Shl` that spins a vector leftward by a given amount.
+ ///
+ /// ```
+ /// use std::ops::Shl;
+ ///
+ /// #[derive(PartialEq, Debug)]
+ /// struct SpinVector<T: Clone> {
+ ///     vec: Vec<T>,
+ /// }
+ ///
+ /// impl<T: Clone> Shl<usize> for SpinVector<T> {
+ ///     type Output = Self;
+ ///
+ ///     fn shl(self, rhs: usize) -> SpinVector<T> {
+ ///         // rotate the vector by `rhs` places
+ ///         let (a, b) = self.vec.split_at(rhs);
+ ///         let mut spun_vector: Vec<T> = vec![];
+ ///         spun_vector.extend_from_slice(b);
+ ///         spun_vector.extend_from_slice(a);
+ ///         SpinVector { vec: spun_vector }
  ///     }
  /// }
  ///
  /// fn main() {
- ///     Foo << Foo;
+ ///     assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } << 2,
+ ///                SpinVector { vec: vec![2, 3, 4, 0, 1] });
  /// }
  /// ```
  #[lang = "shl"]
@@@ -1106,25 -953,54 +1135,54 @@@ shl_impl_all! { u8 u16 u32 u64 usize i
  ///
  /// # Examples
  ///
- /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up
- /// calling `shr`, and therefore, `main` prints `Shifting right!`.
+ /// An implementation of `Shr` that lifts the `>>` operation on integers to a
+ /// `Scalar` struct.
  ///
  /// ```
  /// use std::ops::Shr;
  ///
- /// struct Foo;
+ /// #[derive(PartialEq, Debug)]
+ /// struct Scalar(usize);
  ///
- /// impl Shr<Foo> for Foo {
- ///     type Output = Foo;
+ /// impl Shr<Scalar> for Scalar {
+ ///     type Output = Self;
  ///
- ///     fn shr(self, _rhs: Foo) -> Foo {
- ///         println!("Shifting right!");
- ///         self
+ ///     fn shr(self, Scalar(rhs): Self) -> Scalar {
+ ///         let Scalar(lhs) = self;
+ ///         Scalar(lhs >> rhs)
+ ///     }
+ /// }
+ /// fn main() {
+ ///     assert_eq!(Scalar(16) >> Scalar(2), Scalar(4));
+ /// }
+ /// ```
+ ///
+ /// An implementation of `Shr` that spins a vector rightward by a given amount.
+ ///
+ /// ```
+ /// use std::ops::Shr;
+ ///
+ /// #[derive(PartialEq, Debug)]
+ /// struct SpinVector<T: Clone> {
+ ///     vec: Vec<T>,
+ /// }
+ ///
+ /// impl<T: Clone> Shr<usize> for SpinVector<T> {
+ ///     type Output = Self;
+ ///
+ ///     fn shr(self, rhs: usize) -> SpinVector<T> {
+ ///         // rotate the vector by `rhs` places
+ ///         let (a, b) = self.vec.split_at(self.vec.len() - rhs);
+ ///         let mut spun_vector: Vec<T> = vec![];
+ ///         spun_vector.extend_from_slice(b);
+ ///         spun_vector.extend_from_slice(a);
+ ///         SpinVector { vec: spun_vector }
  ///     }
  /// }
  ///
  /// fn main() {
- ///     Foo >> Foo;
+ ///     assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } >> 2,
+ ///                SpinVector { vec: vec![3, 4, 0, 1, 2] });
  /// }
  /// ```
  #[lang = "shr"]
@@@ -1234,36 -1110,25 +1292,36 @@@ add_assign_impl! { usize u8 u16 u32 u6
  ///
  /// # Examples
  ///
 -/// A trivial implementation of `SubAssign`. When `Foo -= Foo` happens, it ends up
 -/// calling `sub_assign`, and therefore, `main` prints `Subtracting!`.
 +/// This example creates a `Point` struct that implements the `SubAssign`
 +/// trait, and then demonstrates sub-assigning to a mutable `Point`.
  ///
  /// ```
  /// use std::ops::SubAssign;
  ///
 -/// struct Foo;
 +/// #[derive(Debug)]
 +/// struct Point {
 +///     x: i32,
 +///     y: i32,
 +/// }
  ///
 -/// impl SubAssign for Foo {
 -///     fn sub_assign(&mut self, _rhs: Foo) {
 -///         println!("Subtracting!");
 +/// impl SubAssign for Point {
 +///     fn sub_assign(&mut self, other: Point) {
 +///         *self = Point {
 +///             x: self.x - other.x,
 +///             y: self.y - other.y,
 +///         };
  ///     }
  /// }
  ///
 -/// # #[allow(unused_assignments)]
 -/// fn main() {
 -///     let mut foo = Foo;
 -///     foo -= Foo;
 +/// impl PartialEq for Point {
 +///     fn eq(&self, other: &Self) -> bool {
 +///         self.x == other.x && self.y == other.y
 +///     }
  /// }
 +///
 +/// let mut point = Point { x: 3, y: 3 };
 +/// point -= Point { x: 2, y: 3 };
 +/// assert_eq!(point, Point {x: 1, y: 0});
  /// ```
  #[lang = "sub_assign"]
  #[stable(feature = "op_assign_traits", since = "1.8.0")]
@@@ -1682,44 -1547,28 +1740,44 @@@ shr_assign_impl_all! { u8 u16 u32 u64 u
  ///
  /// # Examples
  ///
 -/// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up
 -/// calling `index`, and therefore, `main` prints `Indexing!`.
 +/// This example implements `Index` on a read-only `NucleotideCount` container,
 +/// enabling individual counts to be retrieved with index syntax.
  ///
  /// ```
  /// use std::ops::Index;
  ///
 -/// #[derive(Copy, Clone)]
 -/// struct Foo;
 -/// struct Bar;
 +/// enum Nucleotide {
 +///     A,
 +///     C,
 +///     G,
 +///     T,
 +/// }
  ///
 -/// impl Index<Bar> for Foo {
 -///     type Output = Foo;
 +/// struct NucleotideCount {
 +///     a: usize,
 +///     c: usize,
 +///     g: usize,
 +///     t: usize,
 +/// }
  ///
 -///     fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
 -///         println!("Indexing!");
 -///         self
 +/// impl Index<Nucleotide> for NucleotideCount {
 +///     type Output = usize;
 +///
 +///     fn index(&self, nucleotide: Nucleotide) -> &usize {
 +///         match nucleotide {
 +///             Nucleotide::A => &self.a,
 +///             Nucleotide::C => &self.c,
 +///             Nucleotide::G => &self.g,
 +///             Nucleotide::T => &self.t,
 +///         }
  ///     }
  /// }
  ///
 -/// fn main() {
 -///     Foo[Bar];
 -/// }
 +/// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
 +/// assert_eq!(nucleotide_count[Nucleotide::A], 14);
 +/// assert_eq!(nucleotide_count[Nucleotide::C], 9);
 +/// assert_eq!(nucleotide_count[Nucleotide::G], 10);
 +/// assert_eq!(nucleotide_count[Nucleotide::T], 12);
  /// ```
  #[lang = "index"]
  #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
@@@ -1940,33 -1789,17 +1998,33 @@@ impl<Idx: PartialOrd<Idx>> RangeFrom<Id
  ///
  /// It cannot serve as an iterator because it doesn't have a starting point.
  ///
 +/// # Examples
 +///
 +/// The `..{integer}` syntax is a `RangeTo`:
 +///
 +/// ```
 +/// assert_eq!((..5), std::ops::RangeTo{ end: 5 });
  /// ```
 -/// fn main() {
 -///     assert_eq!((..5), std::ops::RangeTo{ end: 5 });
  ///
 -///     let arr = [0, 1, 2, 3];
 -///     assert_eq!(arr[ .. ], [0,1,2,3]);
 -///     assert_eq!(arr[ ..3], [0,1,2  ]);  // RangeTo
 -///     assert_eq!(arr[1.. ], [  1,2,3]);
 -///     assert_eq!(arr[1..3], [  1,2  ]);
 +/// It does not have an `IntoIterator` implementation, so you can't use it in a
 +/// `for` loop directly. This won't compile:
 +///
 +/// ```ignore
 +/// for i in ..5 {
 +///     // ...
  /// }
  /// ```
 +///
 +/// When used as a slicing index, `RangeTo` produces a slice of all array
 +/// elements before the index indicated by `end`.
 +///
 +/// ```
 +/// let arr = [0, 1, 2, 3];
 +/// assert_eq!(arr[ .. ], [0,1,2,3]);
 +/// assert_eq!(arr[ ..3], [0,1,2  ]);  // RangeTo
 +/// assert_eq!(arr[1.. ], [  1,2,3]);
 +/// assert_eq!(arr[1..3], [  1,2  ]);
 +/// ```
  #[derive(Copy, Clone, PartialEq, Eq, Hash)]
  #[stable(feature = "rust1", since = "1.0.0")]
  pub struct RangeTo<Idx> {
@@@ -2094,31 -1927,16 +2152,31 @@@ impl<Idx: PartialOrd<Idx>> RangeInclusi
  ///
  /// # Examples
  ///
 +/// The `...{integer}` syntax is a `RangeToInclusive`:
 +///
  /// ```
  /// #![feature(inclusive_range,inclusive_range_syntax)]
 -/// fn main() {
 -///     assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
 +/// assert_eq!((...5), std::ops::RangeToInclusive{ end: 5 });
 +/// ```
  ///
 -///     let arr = [0, 1, 2, 3];
 -///     assert_eq!(arr[ ...2], [0,1,2  ]);  // RangeToInclusive
 -///     assert_eq!(arr[1...2], [  1,2  ]);
 +/// It does not have an `IntoIterator` implementation, so you can't use it in a
 +/// `for` loop directly. This won't compile:
 +///
 +/// ```ignore
 +/// for i in ...5 {
 +///     // ...
  /// }
  /// ```
 +///
 +/// When used as a slicing index, `RangeToInclusive` produces a slice of all
 +/// array elements up to and including the index indicated by `end`.
 +///
 +/// ```
 +/// #![feature(inclusive_range_syntax)]
 +/// let arr = [0, 1, 2, 3];
 +/// assert_eq!(arr[ ...2], [0,1,2  ]);  // RangeToInclusive
 +/// assert_eq!(arr[1...2], [  1,2  ]);
 +/// ```
  #[derive(Copy, Clone, PartialEq, Eq, Hash)]
  #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
  pub struct RangeToInclusive<Idx> {
@@@ -2267,35 -2085,6 +2325,35 @@@ impl<'a, T: ?Sized> DerefMut for &'a mu
  }
  
  /// A version of the call operator that takes an immutable receiver.
 +///
 +/// # Examples
 +///
 +/// Closures automatically implement this trait, which allows them to be
 +/// invoked. Note, however, that `Fn` takes an immutable reference to any
 +/// captured variables. To take a mutable capture, implement [`FnMut`], and to
 +/// consume the capture, implement [`FnOnce`].
 +///
 +/// [`FnMut`]: trait.FnMut.html
 +/// [`FnOnce`]: trait.FnOnce.html
 +///
 +/// ```
 +/// let square = |x| x * x;
 +/// assert_eq!(square(5), 25);
 +/// ```
 +///
 +/// Closures can also be passed to higher-level functions through a `Fn`
 +/// parameter (or a `FnMut` or `FnOnce` parameter, which are supertraits of
 +/// `Fn`).
 +///
 +/// ```
 +/// fn call_with_one<F>(func: F) -> usize
 +///     where F: Fn(usize) -> usize {
 +///     func(1)
 +/// }
 +///
 +/// let double = |x| x * 2;
 +/// assert_eq!(call_with_one(double), 2);
 +/// ```
  #[lang = "fn"]
  #[stable(feature = "rust1", since = "1.0.0")]
  #[rustc_paren_sugar]
@@@ -2307,40 -2096,6 +2365,40 @@@ pub trait Fn<Args> : FnMut<Args> 
  }
  
  /// A version of the call operator that takes a mutable receiver.
 +///
 +/// # Examples
 +///
 +/// Closures that mutably capture variables automatically implement this trait,
 +/// which allows them to be invoked.
 +///
 +/// ```
 +/// let mut x = 5;
 +/// {
 +///     let mut square_x = || x *= x;
 +///     square_x();
 +/// }
 +/// assert_eq!(x, 25);
 +/// ```
 +///
 +/// Closures can also be passed to higher-level functions through a `FnMut`
 +/// parameter (or a `FnOnce` parameter, which is a supertrait of `FnMut`).
 +///
 +/// ```
 +/// fn do_twice<F>(mut func: F)
 +///     where F: FnMut()
 +/// {
 +///     func();
 +///     func();
 +/// }
 +///
 +/// let mut x: usize = 1;
 +/// {
 +///     let add_two_to_x = || x += 2;
 +///     do_twice(add_two_to_x);
 +/// }
 +///
 +/// assert_eq!(x, 5);
 +/// ```
  #[lang = "fn_mut"]
  #[stable(feature = "rust1", since = "1.0.0")]
  #[rustc_paren_sugar]
@@@ -2352,41 -2107,6 +2410,41 @@@ pub trait FnMut<Args> : FnOnce<Args> 
  }
  
  /// A version of the call operator that takes a by-value receiver.
 +///
 +/// # Examples
 +///
 +/// By-value closures automatically implement this trait, which allows them to
 +/// be invoked.
 +///
 +/// ```
 +/// let x = 5;
 +/// let square_x = move || x * x;
 +/// assert_eq!(square_x(), 25);
 +/// ```
 +///
 +/// By-value Closures can also be passed to higher-level functions through a
 +/// `FnOnce` parameter.
 +///
 +/// ```
 +/// fn consume_with_relish<F>(func: F)
 +///     where F: FnOnce() -> String
 +/// {
 +///     // `func` consumes its captured variables, so it cannot be run more
 +///     // than once
 +///     println!("Consumed: {}", func());
 +///
 +///     println!("Delicious!");
 +///
 +///     // Attempting to invoke `func()` again will throw a `use of moved
 +///     // value` error for `func`
 +/// }
 +///
 +/// let x = String::from("x");
 +/// let consume_and_return_x = move || x;
 +/// consume_with_relish(consume_and_return_x);
 +///
 +/// // `consume_and_return_x` can no longer be invoked at this point
 +/// ```
  #[lang = "fn_once"]
  #[stable(feature = "rust1", since = "1.0.0")]
  #[rustc_paren_sugar]
@@@ -2402,6 -2122,9 +2460,6 @@@ pub trait FnOnce<Args> 
  }
  
  mod impls {
 -    use marker::Sized;
 -    use super::{Fn, FnMut, FnOnce};
 -
      #[stable(feature = "rust1", since = "1.0.0")]
      impl<'a,A,F:?Sized> Fn<A> for &'a F
          where F : Fn<A>
@@@ -2606,74 -2329,3 +2664,74 @@@ pub trait BoxPlace<Data: ?Sized> : Plac
      /// Creates a globally fresh place.
      fn make_place() -> Self;
  }
 +
 +/// A trait for types which have success and error states and are meant to work
 +/// with the question mark operator.
 +/// When the `?` operator is used with a value, whether the value is in the
 +/// success or error state is determined by calling `translate`.
 +///
 +/// This trait is **very** experimental, it will probably be iterated on heavily
 +/// before it is stabilised. Implementors should expect change. Users of `?`
 +/// should not rely on any implementations of `Carrier` other than `Result`,
 +/// i.e., you should not expect `?` to continue to work with `Option`, etc.
 +#[unstable(feature = "question_mark_carrier", issue = "31436")]
 +pub trait Carrier {
 +    /// The type of the value when computation succeeds.
 +    type Success;
 +    /// The type of the value when computation errors out.
 +    type Error;
 +
 +    /// Create a `Carrier` from a success value.
 +    fn from_success(Self::Success) -> Self;
 +
 +    /// Create a `Carrier` from an error value.
 +    fn from_error(Self::Error) -> Self;
 +
 +    /// Translate this `Carrier` to another implementation of `Carrier` with the
 +    /// same associated types.
 +    fn translate<T>(self) -> T where T: Carrier<Success=Self::Success, Error=Self::Error>;
 +}
 +
 +#[unstable(feature = "question_mark_carrier", issue = "31436")]
 +impl<U, V> Carrier for Result<U, V> {
 +    type Success = U;
 +    type Error = V;
 +
 +    fn from_success(u: U) -> Result<U, V> {
 +        Ok(u)
 +    }
 +
 +    fn from_error(e: V) -> Result<U, V> {
 +        Err(e)
 +    }
 +
 +    fn translate<T>(self) -> T
 +        where T: Carrier<Success=U, Error=V>
 +    {
 +        match self {
 +            Ok(u) => T::from_success(u),
 +            Err(e) => T::from_error(e),
 +        }
 +    }
 +}
 +
 +struct _DummyErrorType;
 +
 +impl Carrier for _DummyErrorType {
 +    type Success = ();
 +    type Error = ();
 +
 +    fn from_success(_: ()) -> _DummyErrorType {
 +        _DummyErrorType
 +    }
 +
 +    fn from_error(_: ()) -> _DummyErrorType {
 +        _DummyErrorType
 +    }
 +
 +    fn translate<T>(self) -> T
 +        where T: Carrier<Success=(), Error=()>
 +    {
 +        T::from_success(())
 +    }
 +}