pub trait IndexMut<Idx>:Index<Idx>where Idx: ?Sized,{ // Required method fnindex_mut(&mut self, index: Idx) -> &mut Self::Output;}Expand description
Used for indexing operations (container[index]) in mutable contexts.
container[index] is actually syntactic sugar for*container.index_mut(index), but only when used as a mutable value. Ifan immutable value is requested, theIndex trait is used instead. Thisallows nice things such asv[index] = value.
§Examples
A very simple implementation of aBalance struct that has two sides, whereeach can be indexed mutably and immutably.
usestd::ops::{Index, IndexMut};#[derive(Debug)]enumSide { Left, Right,}#[derive(Debug, PartialEq)]enumWeight { Kilogram(f32), Pound(f32),}structBalance {publeft: Weight,pubright: Weight,}implIndex<Side>forBalance {typeOutput = Weight;fnindex(&self, index: Side) ->&Self::Output {println!("Accessing {index:?}-side of balance immutably");matchindex { Side::Left =>&self.left, Side::Right =>&self.right, } }}implIndexMut<Side>forBalance {fnindex_mut(&mutself, index: Side) ->&mutSelf::Output {println!("Accessing {index:?}-side of balance mutably");matchindex { Side::Left =>&mutself.left, Side::Right =>&mutself.right, } }}letmutbalance = Balance { right: Weight::Kilogram(2.5), left: Weight::Pound(1.5),};// In this case, `balance[Side::Right]` is sugar for// `*balance.index(Side::Right)`, since we are only *reading*// `balance[Side::Right]`, not writing it.assert_eq!(balance[Side::Right], Weight::Kilogram(2.5));// However, in this case `balance[Side::Left]` is sugar for// `*balance.index_mut(Side::Left)`, since we are writing// `balance[Side::Left]`.balance[Side::Left] = Weight::Kilogram(3.0);