Modify syntax to let you put mut
in right hands when you instantiate structs to refine its mutability.
Mutability of a
itself but not a.*
s.
let mut a = A { x: 0, y: 1 };
Mutability of a.x
.
let a = A { mut x: 0, y: 1 };
Mutability of all a.*
s.
let a = mut A { x: 0, y: 1 };
let a = A { mut x: 0, y: 1 };
a.x = 1; // Ok
a.y = 2; // Error
// Mutability doesn't change by the move because it's internal to the compound data.
let b = a;
b.x = 2; // Ok
// Here `mut` simply declars `y` is mutable, is not a part of destructuring pattern.
let A { x, mut y } = a;
x = 3; // Error
y = 4; // Ok
// `a` doesn't match the type `mut A` as it has an immutable field `y`
fn f(b: &mut A) {
b.x = 2;
}
f(&a) // Error
// Syntax for the corresponding type for `a`
fn f(b: &A { mut x }) {
b.x = 2;
}
f(&a) // Ok
- You can separate visibility and mutability. For now visiblity (
pub
) implies mutability. With this, visible means readable but not necessarily writable (mutable). - You don't need to write get/set functions every time, or wrap field types with
Cell
orRefCell
. - Solve https://internals.rust-lang.org/t/pre-rfc-read-only-visibility/11280.
Mutability of a
itself but not a.*
s.
let mut a = (20, 20);
Mutability of a.0
.
let a = (mut 20, 20);
Mutability of all a.*
s.
let a = mut (20, 20);
Field shadowing (holding values in fields only in a scope), if interesting.
let a.x = 2;
let a.0 = 30;
let mut a = 1;
--- mutability about `a`
fn f(mut a: i32) {}
--- mutability about `a`
// for a callar, it passes `b` and recieves _
let mut a: _ = f(mut b);
// for a callee, it recieves `b` and passes _
fn f(mut b: mut ) -> mut {}
What needs to be matched is _ and _, and _ and _
Where is the ownership? What is visibility in this case?
The difference between &mut
s and Cell
s are whether they're static or dynamic.
a[x] = 2;