Skip to content

Instantly share code, notes, and snippets.

@rinarakaki
Last active January 19, 2023 02:44
Show Gist options
  • Save rinarakaki/96b9abcf359a514873b4e9078189495a to your computer and use it in GitHub Desktop.
Save rinarakaki/96b9abcf359a514873b4e9078189495a to your computer and use it in GitHub Desktop.
Structs' field-level mutability at instantiation (not at definition)

Summary

Modify syntax to let you put mut in right hands when you instantiate structs to refine its mutability.

Syntax

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 };

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;
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

Motivation

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;

To Mention (Rationale)

Left-hand mutability is not right-hand one

let mut a = 1;
    --- mutability about `a`

fn f(mut a: i32) {}
     --- mutability about `a`

Caller/callee × pass/recieve = 4 different mutability

// 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?

Rust = (unique × mutable | non-unique × immutable) = unique ≃ mutable

The difference between &muts and Cells are whether they're static or dynamic.

Fn, FnMut, FnOnce

Vec and Map

a[x] = 2;

Refutabiluty in pattern matching