@@ -1498,28 +1498,44 @@ shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1498
1498
///
1499
1499
/// # Examples
1500
1500
///
1501
- /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up
1502
- /// calling `index`, and therefore, `main` prints `Indexing!` .
1501
+ /// This example implements `Index` on a read-only `NucleotideCount` container,
1502
+ /// enabling individual counts to be retrieved with index syntax .
1503
1503
///
1504
1504
/// ```
1505
1505
/// use std::ops::Index;
1506
1506
///
1507
- /// #[derive(Copy, Clone)]
1508
- /// struct Foo;
1509
- /// struct Bar;
1507
+ /// enum Nucleotide {
1508
+ /// A,
1509
+ /// C,
1510
+ /// G,
1511
+ /// T,
1512
+ /// }
1510
1513
///
1511
- /// impl Index<Bar> for Foo {
1512
- /// type Output = Foo;
1514
+ /// struct NucleotideCount {
1515
+ /// a: usize,
1516
+ /// c: usize,
1517
+ /// g: usize,
1518
+ /// t: usize,
1519
+ /// }
1513
1520
///
1514
- /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1515
- /// println!("Indexing!");
1516
- /// self
1521
+ /// impl Index<Nucleotide> for NucleotideCount {
1522
+ /// type Output = usize;
1523
+ ///
1524
+ /// fn index(&self, nucleotide: Nucleotide) -> &usize {
1525
+ /// match nucleotide {
1526
+ /// Nucleotide::A => &self.a,
1527
+ /// Nucleotide::C => &self.c,
1528
+ /// Nucleotide::G => &self.g,
1529
+ /// Nucleotide::T => &self.t,
1530
+ /// }
1517
1531
/// }
1518
1532
/// }
1519
1533
///
1520
- /// fn main() {
1521
- /// Foo[Bar];
1522
- /// }
1534
+ /// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
1535
+ /// assert_eq!(nucleotide_count[Nucleotide::A], 14);
1536
+ /// assert_eq!(nucleotide_count[Nucleotide::C], 9);
1537
+ /// assert_eq!(nucleotide_count[Nucleotide::G], 10);
1538
+ /// assert_eq!(nucleotide_count[Nucleotide::T], 12);
1523
1539
/// ```
1524
1540
#[ lang = "index" ]
1525
1541
#[ rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`" ]
0 commit comments