It is not intuitive for me why a program like
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();
}
compiles and runs without any problems, but a program like
enum State {
Testing([u8; 16]),
}
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();
}
when compiling with an error
error [E0502]: cannot be taken *selfas immutable, because it is self.state.0also borrowed as mutable
Since both programs perform essentially the same thing, the second does not seem to be somehow more dangerous in terms of memory. I know that there must be something about the rules for borrowing and defining the scope that I have to miss, but I have no idea what.
source
share