Rust笔记 - Index && IndexMut trait

648 阅读1分钟

在Rust中实现Index 和 IndexMut trait 就是实现对[]操作符的使用。下面看一下定义:

trait Index<Idx> {
    type Output: ?Sized;
    fn index(&self, index: Idx) -> &Self::Output;
}

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

下面一个实现的例子:

struct Any<T> {
    width: usize,
    con: Vec<T>,
}

impl<T> std::ops::Index<usize> for Any<T> {
    type Output = [T];
    fn index(&self, index: usize) -> &[T] {
        let start = index * self.width;
        &self.con[start..start + self.width]
    }
}

impl<T> std::ops::IndexMut<usize> for Any<T> {
    fn index_mut(&mut self, index: usize) -> &mut [T] {
        let start = index * self.width;
        &mut self.con[start..start + self.width]
    }
}

fn main() {
    let mut a = Any { width: 2, con: vec!{1, 2, 3, 4, 5, 6} };
    assert!(a[0] == [1, 2]);

    let b = &mut a[1];
    b[0] = 7;
    assert!(b == [7, 4]);
}

上面的例子就是实现对vector进行再切片的功能。