What if mutability was type-based?

I think the current Rust's approach works better, and it's entirely sufficient. Immutability is not a goal in itself, only a tool.

Immutability is a tool to prevent mistakes caused by unexpected mutation, and it's unexpected primarily when it's coming from shared mutable state. Some languages fix it by forbidding mutability entirely, but Rust fixes it by forbidding sharing when the data is mutable. With unique ownership, it turns out to be sufficient for immutability/exclusivity to be a property of how the data is accessed, not the data itself.

This has incredibly nice property of being able to easily initialize data while it's mutable, then share it immutably, and even get it back as mutable to update or destructure it. In other languages that I know, going from mutable to immutable is always one-way-only, and loses this flexibility.

4 Likes

What is the benefit?

This is how C++ works and it causes a lot of trouble there compared to how it works in Rust.

References are separate types, and they can be nested. Consider &T as a shortcut for Ref<T> and &mut T as a shortcut for MutRef<T>.For any type T, there is &T, &mut T, &&T, &&mut T, &mut &T, &mut &mut T, etc.

This is valid:

fn main() {
    let m = &mut &mut & &mut &&mut &&&&mut "Hello, world!";
    println!("{}", m);
}

Sometimes, it's useful to write a function like this

fn foo(mut x: i32) {
    x += 1;
    return x;
}

Making a parameter mutable like this, without using a mutable reference, should probably not be a breaking change, but changing the type instead would be breaking.