Summary
Modify syntax to let you put mut
in right hands when you instantiate structs to refine their mutability.
Syntax
The mutability of a
itself but not of each a.*
.
let mut a = A { x: 0, y: 1 };
The mutability of a.x
.
let a = A { mut x: 0, y: 1 };
The mutability of each a.*
.
let a = mut A { x: 0, y: 1 };
Examples
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; // Ok
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
// The syntax for the corresponding type for `a`
fn f(b: &A { mut x }) {
b.x = 2;
}
f(&a) // Ok
Motivation
- You can separate visibility and mutability. For now, visibility (
pub
) implies mutability. With this change, visible means readable but not necessarily writable (mutable). - You don't ever need to write get/set functions, nor wrap fields with
Cell
orRefCell
. - Solve [Pre-RFC] read-only visibility.
Tuples
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);
Advanced
Field shadowing (holding values in fields only in a scope), if interesting.
let a.x = 2;
let a.0 = 30;