Skip to content

Confusing error message when trying to implement a shared mutable state #55826

@lovasoa

Description

@lovasoa

Let's say I am a rust beginner coming from another language, and I want to write a simple multi-threaded program in rust.

So I write this simple function :

fn simple() -> u8 {
    let mut x = 0;
    std::thread::spawn(|| {
        x += 1;
    });
    x += 1;
    x
}

One of the selling points of rust is being able to prevent data races, so it should be able to explain in details what is wrong with this function. However, it gives a confusing error message.

It does not compile, and the compiler returns :

closure may outlive the current function, but it borrows x, which is owned by the current function
help: to force the closure to take ownership of x (and any other referenced variables), use the move keyword

And if I look up the detailed error message in the error book (here: https://doc.rust-lang.org/error-index.html#E0373), it also tells me to add a move in front of the closure.

I think this is confusing. Obviously, the right thing to do here is to use a mutex, but this is not mentioned neither in the error message, nor in the error book.

Maybe the error should also say something like

If you need to use x both in the current function and in the closure, than you may have to use a form of shared state concurrency

It would be even nicer if the compiler could detect that we are using x after the litigious function, and thus not talk about move at all.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions