pub trait Index<Idx>where Idx: ?Sized,{ typeOutput: ?Sized; // Required method fnindex(&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 ofvalue implementsCopy.
§Examples
The following example implementsIndex on a read-onlyNucleotideCountcontainer, enabling individual counts to be retrieved with index syntax.
usestd::ops::Index;enumNucleotide { A, C, G, T,}structNucleotideCount { a: usize, c: usize, g: usize, t: usize,}implIndex<Nucleotide>forNucleotideCount {typeOutput = usize;fnindex(&self, nucleotide: Nucleotide) ->&Self::Output {matchnucleotide { Nucleotide::A =>&self.a, Nucleotide::C =>&self.c, Nucleotide::G =>&self.g, Nucleotide::T =>&self.t, } }}letnucleotide_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);