如何在结构字段上创建可变的迭代器

因此,我正在使用Rust开发一款小型NES模拟器,并且尝试使用状态寄存器。寄存器是一个结构,其中包含一些包含布尔的字段(标志),该寄存器本身是CPU结构的一部分。现在,我想遍历这些字段并根据我执行的某些指令设置布尔值。但是,不能实现可变的迭代器,我实现了into_iter()函数,并且可以遍历字段以获取/打印布尔值,但是如何在结构本身内对这些值进行突变?这有可能吗?

pub struct StatusRegister {
    CarryFlag: bool,
    ZeroFlag: bool,
    OverflowFlag: bool
}

impl StatusRegister {

    fn new() -> Self {
        StatusRegister {
        CarryFlag: true,
        ZeroFlag: false,
        OverflowFlag: true
        }
    }
}

impl<'a> IntoIterator for &'a StatusRegister {
    type Item = bool;
    type IntoIter = StatusRegisterIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        StatusRegisterIterator {
            status: self,
            index: 0
        }
    }
}

pub struct StatusRegisterIterator<'a> {
    status: &'a StatusRegister,
    index: usize
}

impl<'a> Iterator for StatusRegisterIterator<'a> {
    type Item = bool;

    fn next(&mut self) -> Option<bool> {
        let result = match self.index {
        0 => self.status.CarryFlag,
        1 => self.status.ZeroFlag,
        2 => self.status.OverflowFlag,
        _ => return None,
        };
    self.index += 1;
    Some(result)
    }
}

pub struct CPU {
    pub memory: [u8; 0xffff],
    pub status: StatusRegister,
}

impl CPU {

    pub fn new() -> CPU  {
        let memory = [0; 0xFFFF];
        CPU {
            memory,
            status: StatusRegister::new(),
        }
    }

    fn execute(&mut self) {

        let mut shifter = 0b1000_0000;
        for status in self.status.into_iter() {
            //mute status here!
            println!("{}",status);
            shifter <<= 1;
        }
    }
}

fn main() {

    let mut cpu = CPU::new();
    cpu.execute();
}

评论