@@ -1550,28 +1550,44 @@ shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1550
1550
///
1551
1551
/// # Examples
1552
1552
///
1553
- /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up
1554
- /// calling `index`, and therefore, `main` prints `Indexing!` .
1553
+ /// This example implements `Index` on a read-only `NucleotideCount` container,
1554
+ /// enabling individual counts to be retrieved with index syntax .
1555
1555
///
1556
1556
/// ```
1557
1557
/// use std::ops::Index;
1558
1558
///
1559
- /// #[derive(Copy, Clone)]
1560
- /// struct Foo;
1561
- /// struct Bar;
1559
+ /// enum Nucleotide {
1560
+ /// A,
1561
+ /// C,
1562
+ /// G,
1563
+ /// T,
1564
+ /// }
1562
1565
///
1563
- /// impl Index<Bar> for Foo {
1564
- /// type Output = Foo;
1566
+ /// struct NucleotideCount {
1567
+ /// a: usize,
1568
+ /// c: usize,
1569
+ /// g: usize,
1570
+ /// t: usize,
1571
+ /// }
1565
1572
///
1566
- /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1567
- /// println!("Indexing!");
1568
- /// self
1573
+ /// impl Index<Nucleotide> for NucleotideCount {
1574
+ /// type Output = usize;
1575
+ ///
1576
+ /// fn index(&self, nucleotide: Nucleotide) -> &usize {
1577
+ /// match nucleotide {
1578
+ /// Nucleotide::A => &self.a,
1579
+ /// Nucleotide::C => &self.c,
1580
+ /// Nucleotide::G => &self.g,
1581
+ /// Nucleotide::T => &self.t,
1582
+ /// }
1569
1583
/// }
1570
1584
/// }
1571
1585
///
1572
- /// fn main() {
1573
- /// Foo[Bar];
1574
- /// }
1586
+ /// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
1587
+ /// assert_eq!(nucleotide_count[Nucleotide::A], 14);
1588
+ /// assert_eq!(nucleotide_count[Nucleotide::C], 9);
1589
+ /// assert_eq!(nucleotide_count[Nucleotide::G], 10);
1590
+ /// assert_eq!(nucleotide_count[Nucleotide::T], 12);
1575
1591
/// ```
1576
1592
#[ lang = "index" ]
1577
1593
#[ rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`" ]
0 commit comments