Trait std::ops::IndexMut1.0.0[][src]

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

用于可变上下文中的索引操作 (container[index])。

container[index] 实际上是 *container.index_mut(index) 的语法糖,但仅当用作变量值时。 如果请求一个不可变值,则使用 Index trait。 这允许使用诸如 v[index] = value 之类的好东西。

Examples

Balance 结构体的非常简单的实现,它具有两个面,每个面都可以可变和不可变地进行索引。

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(&self, index: Side) -> &Self::Output {
        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(&mut self, index: Side) -> &mut Self::Output {
        println!("Accessing {:?}-side of balance mutably", index);
        match index {
            Side::Left => &mut self.left,
            Side::Right => &mut self.right,
        }
    }
}

let mut balance = Balance {
    right: Weight::Kilogram(2.5),
    left: Weight::Pound(1.5),
};

// 在这种情况下,`balance[Side::Right]` 是 `*balance.index(Side::Right)` 的糖,因为我们只是* 读*`balance[Side::Right]`,而不是写 `balance[Side::Right]`。
assert_eq!(balance[Side::Right], Weight::Kilogram(2.5));

// 但是,在这种情况下,`balance[Side::Left]` 是 `*balance.index_mut(Side::Left)` 的糖,因为我们正在编写 `balance[Side::Left]`。
balance[Side::Left] = Weight::Kilogram(3.0);
Run

Required methods

执行可变索引 (container[index]) 操作。

Panics

如果索引越界,则可能为 panic。

Implementors