Skip to content

Commit 1dfc5db

Browse files
replace Index example with something more evocative of indexing
r? @steveklabnik
1 parent 7ac11ca commit 1dfc5db

File tree

1 file changed

+29
-13
lines changed

1 file changed

+29
-13
lines changed

src/libcore/ops.rs

+29-13
Original file line numberDiff line numberDiff line change
@@ -1381,28 +1381,44 @@ shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
13811381
///
13821382
/// # Examples
13831383
///
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.
13861386
///
13871387
/// ```
13881388
/// use std::ops::Index;
13891389
///
1390-
/// #[derive(Copy, Clone)]
1391-
/// struct Foo;
1392-
/// struct Bar;
1390+
/// enum Nucleotide {
1391+
/// A,
1392+
/// C,
1393+
/// G,
1394+
/// T,
1395+
/// }
13931396
///
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+
/// }
13961403
///
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+
/// }
14001414
/// }
14011415
/// }
14021416
///
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);
14061422
/// ```
14071423
#[lang = "index"]
14081424
#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]

0 commit comments

Comments
 (0)