W3cubDocs

/Rust

Trait std::ops::IndexMut

pub trait IndexMut<Idx>: Index<Idx> where Idx: ?Sized {
    fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
}

The IndexMut trait is used to specify the functionality of indexing operations like container[index] when used in a mutable context.

container[index] is actually syntactic sugar for *container.index_mut(index), but only when used as a mutable value. If an immutable value is requested, the Index trait is used instead. This allows nice things such as v[index] = value if value implements Copy.

Examples

A very simple implementation of a Balance struct that has two sides, where each can be indexed mutably and immutably.

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<Side> for Balance {
    type Output = Weight;

    fn index<'a>(&'a self, index: Side) -> &'a Weight {
        println!("Accessing {:?}-side of balance immutably", index);
        match index {
            Side::Left => &self.left,
            Side::Right => &self.right,
        }
    }
}

impl IndexMut<Side> for Balance {
    fn index_mut<'a>(&'a mut self, index: Side) -> &'a mut Weight {
        println!("Accessing {:?}-side of balance mutably", index);
        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),
    };

    // 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);
}

Required Methods

The method for the mutable indexing (container[index]) operation

Implementors

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/ops/trait.IndexMut.html