对我来说,像这样的程序为什么会这样并不直观。
#[derive(Debug)]
struct Test {
buf: [u8; 16],
}
impl Test {
fn new() -> Test {
Test {
buf: [0u8; 16],
}
}
fn hi(&mut self) {
self.buf[0] = 'H' as u8;
self.buf[1] = 'i' as u8;
self.buf[2] = '!' as u8;
self.print();
}
fn print(&self) {
println!("{:?}", self);
}
}
fn main() {
Test::new().hi();
}
编译和运行都没有问题,但是像这样的程序
#[derive(Debug)]
enum State {
Testing([u8; 16]),
}
#[derive(Debug)]
struct Test {
state: State,
}
impl Test {
fn new() -> Test {
Test {
state: State::Testing([0u8; 16]),
}
}
fn hi(&mut self) {
match self.state {
State::Testing(ref mut buf) => {
buf[0] = 'H' as u8;
buf[1] = 'i' as u8;
buf[2] = '!' as u8;
self.print();
},
}
}
fn print(&self) {
println!("{:?}", self);
}
}
fn main() {
Test::new().hi();
}
编译时遇到错误,错误信息为
error[E0502]: 因为
self.state.0
被作为可变引用借用了,所以无法将*self
借用为不可变引用
由于这两个程序本质上做相同的事情,第二个程序看起来并不会从内存方面更不安全。我知道一定有关于借用和作用域规则的东西我没有掌握,但是不知道是什么。
if let
进行模式匹配,而不是在这里使用match
,尽管我认为match
更具有“未来可靠性”。 - Matthieu M.State
枚举可能会有更多的变体。 - ljedrz