Skip to content

Error message for mutating field of immutable struct could be clearer #27593

Closed
@ghost

Description

struct Foo {
    pub v: Vec<String>
}

fn main() {
    let f = Foo { v: Vec::new() };
    f.v.push("cat".to_string());
}

The above code gives this compile error:

<anon>:8:5: 8:8 error: cannot borrow immutable field `f.v` as mutable
<anon>:8     f.v.push("cat".to_string());
             ^~~

From my perspective, this implies that the field somehow needs to be marked as mutable, when in fact the user error is that the struct is immutable.

I believe the error message could be improved by saying something like cannot borrow field vof immutable structf as mutable.
#18150 is "related".

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions