我使用prae机箱进行验证,下面的函数给出了错误:
fn advance_rotors(&mut self) {
self.rotors.get()[0].rotate();
let mut iterhandle = self.rotors.iter_mut().peekable(); // Error at iter_mut() #0599
while let Some(el) = iterhandle.next() {
match iterhandle.peek_mut() {
Some(next_rotor) => match el.should_advance_next() {
true => {
next_rotor.rotate(); // This line requires mutable access to next_rotor
}
false => (),
},
None => (),
}
}
}我的结构的定义是:
pub struct Enigma {
reflector: Reflector,
rotors: RotorConfig, // Only mutable via getter and setter functions
}这里感兴趣的结构是RotorConfig,它使用来自prae的define!宏生成。下面是代码:
prae::define! {
#[derive(Debug)]
RotorConfig: Vec<Rotor>; // I need to be able to call the rotate method of each rotor in this vec. This requires mutability
validate(RotorConfigError) |config| {
match config.len(){
3..=4 => (),
_ => return Err(RotorConfigError::Size)
}
match config.iter().unique().count(){
3..=4 =>(),
_ => return Err(RotorConfigError::Duplicate)
}
Ok(())
};
}这个问题源于prae只允许通过getter和setter函数不可变地访问内部表示,以确保内部值的有效性。正如您在我的advance_rotors函数中看到的,我在实现验证之前编写了一个错误,因为我需要不断地调用rotor.rotate。我不知道该如何完成这件事
发布于 2022-06-29 02:17:19
在发布这篇文章之后,我意识到我可以通过使用下面的impl块来提供内部可更改性
impl RotorConfig{
fn advance_rotors(&mut self)
{
self.0[0].rotate();
let mut iterhandle = self.0.iter_mut().peekable();
while let Some(el) = iterhandle.next() {
match iterhandle.peek_mut() {
Some(next_rotor) => match el.should_advance_next() {
true => {
next_rotor.rotate();
}
false => (),
},
None => (),
}
}
}
}如您所见,除了用self.rotors替换self.0之外,函数基本上保持不变。
https://stackoverflow.com/questions/72794999
复制相似问题