trait
IndexMut
Extend Index with mutable indexing so an assignment through brackets can change the referenced element. The Output type comes from Index. Expected stdout (not executed): 30 Common mistake: Implementing IndexMut without the required Index implementation.
Formal Syntax & Structure
rust syntaxrust
impl IndexMut<usize> for ContainerWorking Example
Example Snippetrust
fn main() { use std::ops::{Index, IndexMut}; struct Scores([i32; 2]); impl Index<usize> for Scores { type Output = i32; fn index(&self, i: usize) -> &i32 { &self.0[i] } } impl IndexMut<usize> for Scores { fn index_mut(&mut self, i: usize) -> &mut i32 { &mut self.0[i] } } let mut scores = Scores([12, 24]); scores[1] += 6; println!("{}", scores[1]);}