小编pho*_*oky的帖子

在Rust中实现Index和IndexMut时如何避免冗余代码

目前,std::ops::IndexMut在Rust中的类型上实现特征要求我也实现std::ops::Index特征.这些实现的主体最终几乎完全相同.例如:

use std::ops::{Index, IndexMut};

enum IndexType {
    A,
    B,
}

struct Indexable {
    a: u8,
    b: u8,
}

impl Index<IndexType> for Indexable {
    type Output = u8;
    fn index<'a>(&'a self, idx: IndexType) -> &'a u8 {
        match idx {
            IndexType::A => &self.a,
            IndexType::B => &self.b,
        }
    }
}

impl IndexMut<IndexType> for Indexable {
    fn index_mut<'a>(&'a mut self, idx: IndexType) -> &'a mut u8 {
        match idx {
            IndexType::A => &mut self.a,
            IndexType::B => &mut self.b,
        } …
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
1
解决办法
110
查看次数

标签 统计

rust ×1