Skip to content

Commit 36b8322

Browse files
author
Jonathan Turner
authored
Rollup merge of rust-lang#35864 - matthew-piziak:index-example, r=GuillaumeGomez
replace `Index` example with something more evocative of indexing r? @steveklabnik
2 parents 61f62ec + 1dfc5db commit 36b8322

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
@@ -1550,28 +1550,44 @@ shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
15501550
///
15511551
/// # Examples
15521552
///
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.
15551555
///
15561556
/// ```
15571557
/// use std::ops::Index;
15581558
///
1559-
/// #[derive(Copy, Clone)]
1560-
/// struct Foo;
1561-
/// struct Bar;
1559+
/// enum Nucleotide {
1560+
/// A,
1561+
/// C,
1562+
/// G,
1563+
/// T,
1564+
/// }
15621565
///
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+
/// }
15651572
///
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+
/// }
15691583
/// }
15701584
/// }
15711585
///
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);
15751591
/// ```
15761592
#[lang = "index"]
15771593
#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]

0 commit comments

Comments
 (0)