Index in std::ops - Rust (original) (raw)

Trait Index

1.0.0 · Source

pub trait Index<Idx>

where
    Idx: ?Sized,

{
    type Output: ?Sized;

    // Required method
    fn index(&self, index: Idx) -> &Self::Output;
}

Expand description

Used for indexing operations (container[index]) in immutable contexts.

container[index] is actually syntactic sugar for *container.index(index), but only when used as an immutable value. If a mutable value is requested,IndexMut is used instead. This allows nice things such aslet value = v[index] if the type of value implements Copy.

§Examples

The following example implements Index on a read-only NucleotideCountcontainer, enabling individual counts to be retrieved with index syntax.

use std::ops::Index;

enum Nucleotide {
    A,
    C,
    G,
    T,
}

struct NucleotideCount {
    a: usize,
    c: usize,
    g: usize,
    t: usize,
}

impl Index<Nucleotide> for NucleotideCount {
    type Output = usize;

    fn index(&self, nucleotide: Nucleotide) -> &Self::Output {
        match nucleotide {
            Nucleotide::A => &self.a,
            Nucleotide::C => &self.c,
            Nucleotide::G => &self.g,
            Nucleotide::T => &self.t,
        }
    }
}

let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
assert_eq!(nucleotide_count[Nucleotide::A], 14);
assert_eq!(nucleotide_count[Nucleotide::C], 9);
assert_eq!(nucleotide_count[Nucleotide::G], 10);
assert_eq!(nucleotide_count[Nucleotide::T], 12);

1.0.0 · Source

The returned type after indexing.

1.0.0 · Source

Performs the indexing (container[index]) operation.

§Panics

May panic if the index is out of bounds.