Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
struct Counter {
n: u32,
}
impl Counter {
fn inc(&mut self) {
self.n += 1;
}
}
fn main() {
let c = Counter { n: 0 };
c.inc();
}It does not compile
- Expecting the call to work because the dot adds
&muton its own: that borrow still needs a variable declaredlet mut c, or the call is error E0596. - Expecting a panic at run time: borrows are checked while building, so the compiler rejects
c.inc()and no program is produced.
- Which one-word change makes the program compile, and why does it work?
- Would the call compile if
inctook&self, and couldincstill changen?