1
Fork 0

Rollup merge of #35864 - matthew-piziak:index-example, r=GuillaumeGomez

replace `Index` example with something more evocative of indexing

r? @steveklabnik
This commit is contained in:
Jonathan Turner 2016-08-22 15:34:21 -07:00 committed by GitHub
commit 36b8322a8c

View file

@ -1550,28 +1550,44 @@ shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
/// ///
/// # Examples /// # Examples
/// ///
/// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up /// This example implements `Index` on a read-only `NucleotideCount` container,
/// calling `index`, and therefore, `main` prints `Indexing!`. /// enabling individual counts to be retrieved with index syntax.
/// ///
/// ``` /// ```
/// use std::ops::Index; /// use std::ops::Index;
/// ///
/// #[derive(Copy, Clone)] /// enum Nucleotide {
/// struct Foo; /// A,
/// struct Bar; /// C,
/// G,
/// T,
/// }
/// ///
/// impl Index<Bar> for Foo { /// struct NucleotideCount {
/// type Output = Foo; /// a: usize,
/// c: usize,
/// g: usize,
/// t: usize,
/// }
/// ///
/// fn index<'a>(&'a self, _index: Bar) -> &'a Foo { /// impl Index<Nucleotide> for NucleotideCount {
/// println!("Indexing!"); /// type Output = usize;
/// self ///
/// 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() { /// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
/// Foo[Bar]; /// 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"] #[lang = "index"]
#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"] #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]