If I have an immutable variable bound to a struct, Rust will generally not allow me to mutate the fields of the struct, or the fields of owned child structs.
However, if the field is a mutable reference, Rust will allow me to mutate the referred-to object despite my binding being immutable.
Why is this allowed? Is it not inconsistent with Rust's normal rules for immutability?
Rust won't let me do the same through an immutable reference, so an immutable reference has different behavior than an immutable binding.
Code Example:
struct Bar {
val: i32,
}
struct Foo<'a> {
val: i32,
bar: Bar,
val_ref: &'a mut i32,
}
fn main() {
let mut x = 5;
{
let foo = Foo {
val: 6,
bar: Bar { val: 15 },
val_ref: &mut x
};
// This is illegal because binding is immutable
// foo.val = 7;
// Also illegal to mutate child structures
// foo.bar.val = 20;
// This is fine though... Why?
*foo.val_ref = 10;
let foo_ref = &foo;
// Also illegal to mutate through an immutable reference
//*foo_ref.val_ref = 10;
}
println!("{}", x);
}
*foo.val_ref = 10;
is acceptable, not why the other one's aren't. From my POV, it seems like none of the things in my example should be acceptable through an immutable binding. – something_clever