#![allow(dead_code, deprecated, unused_variables, unused_mut)] use std::ops::{Index, IndexMut}; #[derive(Debug)] enum Side { Left, Right, } #[derive(Debug, PartialEq)] enum Weight { Kilogram(f32), Pound(f32), } struct Balance { pub left: Weight, pub right: Weight, } impl Index for Balance { type Output = Weight; fn index(&self, index: Side) -> &Self::Output { println!("Accessing {index:?}-side of balance immutably"); match index { Side::Left => &self.left, Side::Right => &self.right, } } } impl IndexMut for Balance { fn index_mut(&mut self, index: Side) -> &mut Self::Output { println!("Accessing {index:?}-side of balance mutably"); match index { Side::Left => &mut self.left, Side::Right => &mut self.right, } } } fn main() { let mut balance = Balance { right: Weight::Kilogram(2.5), left: Weight::Pound(1.5), }; assert_eq!(balance[Side::Right], Weight::Kilogram(2.5)); balance[Side::Left] = Weight::Kilogram(3.0); }