trait
Index
Define read indexing for a custom container by returning a reference to its associated Output type. Invalid positions may panic; use a separate checked method when needed. Expected stdout (not executed): 24 Common mistake: Returning an owned element instead of a reference.
Formal Syntax & Structure
rust syntaxrust
impl Index<usize> for ContainerWorking Example
Example Snippetrust
fn main() { use std::ops::Index; struct Scores([i32; 2]); impl Index<usize> for Scores { type Output = i32; fn index(&self, i: usize) -> &i32 { &self.0[i] } } let scores = Scores([12, 24]); println!("{}", scores[1]);}