In the following example the function bar(self)
borrows self
immutably. However, I found out, I could create a mutable borrow, which would then allow me to change its field (example below).
Why it is allowed to make a mutable borrow from self
?
IMO, if the function required mutation, the function signature should say so. I do understand that it doesn't matter in this case, as self
is consumed by the function.
I am confused, because "immutability" is more strict than "mutability" and this looks like something of a privilege escalation. The function signature communicates that self
will not be changed (before being dropped) - but it does.
#[derive(Debug)]
struct Foo(u32);
impl Foo {
fn bar(self) {
// self.0 = 12; // <-- "Error: cannot assign"
let mut self2 = self; // <-- Why allow `mut` here?
self2.0 = 12;
println!("self2: {:?}", self2);
}
}
fn main() {
let a = Foo(42);
println!("a = {:?}", a);
a.bar();
}
Output:
a = Foo(42)
self2: Foo(12)
Errors:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 0.66s
Running `target/debug/playground`
The reason this came up was, that I tried to solve an exercism.io task and was presented a function declaration with an immutable borrow. I thus assumed (barring errors in the question) this should be solved without mutating.