@@ -1381,28 +1381,44 @@ shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
1381
1381
///
1382
1382
/// # Examples
1383
1383
///
1384
- /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up
1385
- /// calling `index`, and therefore, `main` prints `Indexing!` .
1384
+ /// This example implements `Index` on a read-only `NucleotideCount` container,
1385
+ /// enabling individual counts to be retrieved with index syntax .
1386
1386
///
1387
1387
/// ```
1388
1388
/// use std::ops::Index;
1389
1389
///
1390
- /// #[derive(Copy, Clone)]
1391
- /// struct Foo;
1392
- /// struct Bar;
1390
+ /// enum Nucleotide {
1391
+ /// A,
1392
+ /// C,
1393
+ /// G,
1394
+ /// T,
1395
+ /// }
1393
1396
///
1394
- /// impl Index<Bar> for Foo {
1395
- /// type Output = Foo;
1397
+ /// struct NucleotideCount {
1398
+ /// a: usize,
1399
+ /// c: usize,
1400
+ /// g: usize,
1401
+ /// t: usize,
1402
+ /// }
1396
1403
///
1397
- /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
1398
- /// println!("Indexing!");
1399
- /// self
1404
+ /// impl Index<Nucleotide> for NucleotideCount {
1405
+ /// type Output = usize;
1406
+ ///
1407
+ /// fn index(&self, nucleotide: Nucleotide) -> &usize {
1408
+ /// match nucleotide {
1409
+ /// Nucleotide::A => &self.a,
1410
+ /// Nucleotide::C => &self.c,
1411
+ /// Nucleotide::G => &self.g,
1412
+ /// Nucleotide::T => &self.t,
1413
+ /// }
1400
1414
/// }
1401
1415
/// }
1402
1416
///
1403
- /// fn main() {
1404
- /// Foo[Bar];
1405
- /// }
1417
+ /// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
1418
+ /// assert_eq!(nucleotide_count[Nucleotide::A], 14);
1419
+ /// assert_eq!(nucleotide_count[Nucleotide::C], 9);
1420
+ /// assert_eq!(nucleotide_count[Nucleotide::G], 10);
1421
+ /// assert_eq!(nucleotide_count[Nucleotide::T], 12);
1406
1422
/// ```
1407
1423
#[ lang = "index" ]
1408
1424
#[ rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`" ]
0 commit comments