Pre-RFC: Allow mut keyword on struct fields

Summary

Allow the addition of the mut keyword to fields of structs. It should specify whether the field is mutable, if the variable is mutable too.

Motivation

Fields of structs can currently be changed if a) the variable is mutable and b) the code is in a module that fulfills the field's visibility constraint:

  • pub(crate): visible only on the current crate,
  • pub(super): visible only in the current module's parent,
  • pub(in path::to::module): visible only on the specified path and
  • pub(self) ("private", default): visible only in the current module.

However, there are often fields that should not be able to be changed, even from the modules which have access to them - for example identifiers, timestamps or domain-specific stuff.

The addition of this language feature would increase the possibilities of being more specific in the architecture of applications.

Guide-level explanation

struct ChatMessage {
    id: u128,
    chat_id: u128,
    user_id: u128, // error, field is immutable
    mut content: String,
    created_at: SystemTime,
    mut modified_at: Option<SystemTime>,
}

pub fn main() {
    let mut message = ChatMessage { 
        id: 1,
        chat_id: 1,
        user_id: 1,
        content: "Hello World.".to_string(),
        created_at: std::time::SystemTime::now(),
        modified_at: None,
    };

    // User 1 edits the message content.
    // Compiles because "message" is mut and the fields "content" and "modified_at" are mut too.
    message.content = "Hello World!".to_string();
    message.modified_at = Some(std::time::SystemTime::now());

    // User 2 attempts a hostile takeover of the message.
    message.user_id = 2; // error, cannot mutate immutable field `user_id` of mutable variable `message: ChatMessage`
}

How to think about the feature and which impact does it have?

As a rust-developer you can see directly whether or not the value of a struct field can change after it has been created by looking at the struct instead of having to search through any code to see if it will be changed somewhere - and you can be sure that it won't be changed if you don't want it to be.

Sample error message

On the struct field

field is immutable

On the code line which tries to mutate the immutable field

cannot mutate immutable field <field_name> of mutable variable <variable_name>: <struct_name>

Migration guidance

Error code TODO

An immutable struct field was reassigned.

Erroneous code example:

struct Foo {
    a: u32,
}

pub fn main() {
    let mut x = Foo { a: 1 };
    x.a = 5; // error, an immutable struct field was reassigned.
}

By default, struct fields in Rust are immutable. To fix this error, ask yourself if the struct field should really be mutable, and if so, add the keyword mut before the name when you declare the struct field. For example:

struct Foo {
    mut a: u32,
}

pub fn main() {
    let mut x = Foo { a: 1 };
    x.a = 5;
}

Impact on readability, understandability and maintainability

The proposed feature makes code easier to maintain.

Reference-level explanation

TODO

This is the technical portion of the RFC. Explain the design in sufficient detail that:

  • Its interaction with other features is clear.
  • It is reasonably clear how the feature would be implemented.
  • Corner cases are dissected by example.

The section should return to the examples given in the previous section, and explain more fully how the detailed proposal makes those examples work.

Drawbacks

TODO

Why should we not do this?

Rationale and alternatives

TODO

  • Why is this design the best in the space of possible designs?
  • What other designs have been considered and what is the rationale for not choosing them?
  • What is the impact of not doing this?
  • If this is a language proposal, could this be done in a library or macro instead? Does the proposed change make Rust code easier or harder to read, understand, and maintain?

Prior art

TODO

Discuss prior art, both the good and the bad, in relation to this proposal. A few examples of what this can include are:

  • For language, library, cargo, tools, and compiler proposals: Does this feature exist in other programming languages and what experience have their community had?
  • For community proposals: Is this done by some other community and what were their experiences with it?
  • For other teams: What lessons can we learn from what other communities have done here?
  • Papers: Are there any published papers or great posts that discuss this? If you have some relevant papers to refer to, this can serve as a more detailed theoretical background.

This section is intended to encourage you as an author to think about the lessons from other languages, provide readers of your RFC with a fuller picture. If there is no prior art, that is fine - your ideas are interesting to us whether they are brand new or if it is an adaptation from other languages.

Unresolved questions

TODO

  • What parts of the design do you expect to resolve through the RFC process before this gets merged?
  • What parts of the design do you expect to resolve through the implementation of this feature before stabilization?
  • What related issues do you consider out of scope for this RFC that could be addressed in the future independently of the solution that comes out of this RFC?

Future possibilities

TODO

Think about what the natural extension and evolution of your proposal would be and how it would affect the language and project as a whole in a holistic way. Try to use this section as a tool to more fully consider all possible interactions with the project and language in your proposal. Also consider how this all fits into the roadmap for the project and of the relevant sub-team.

This is also a good place to "dump ideas", if they are out of scope for the RFC you are writing but otherwise related.

If you have tried and cannot think of any future possibilities, you may simply state that you cannot think of anything.

This already exists as mut(crate) fields:

7 Likes

And I am revisiting the PR later today!

7 Likes