Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggest reborrowing mutable reference when move error ocurrs #74706

Open
Aaron1011 opened this issue Jul 24, 2020 · 0 comments
Open

Suggest reborrowing mutable reference when move error ocurrs #74706

Aaron1011 opened this issue Jul 24, 2020 · 0 comments
Labels
A-borrow-checker Area: The borrow checker A-suggestion-diagnostics Area: Suggestions generated by the compiler applied by `cargo fix`. C-enhancement Category: An issue proposing an enhancement or a PR with one. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@Aaron1011
Copy link
Member

The following code:

struct Foo;
struct Wrapper<T>(T);

fn use_val<T>(_: &mut T) {}

impl Foo {
    fn call_it(&mut self) {
        use_val(&mut Wrapper(self));
        self;
    }
}

produces the following error:

error[E0382]: use of moved value: `self`
 --> src/lib.rs:9:9
  |
7 |     fn call_it(&mut self) {
  |                --------- move occurs because `self` has type `&mut Foo`, which does not implement the `Copy` trait
8 |         use_val(&mut Wrapper(self));
  |                              ---- value moved here
9 |         self;
  |         ^^^^ value used here after move

error: aborting due to previous error

When self is passed directly to use_val (e.g. use_val(self), a reborrow will automatically be inserted, allowing the code to compile. However, the fact that use_val takes an &mut T means that the compiler won't adjust the inferred type in any way (in this case, &mut Wrapper<&mut Foo>), leading to the move error.

The solution is to add an explicit reborrow (&mut Wrapper(&mut *self)), however, this wasn't obvious to me. It would be useful if the compiler could suggest inserting a reborrow in this situation.

@Aaron1011 Aaron1011 added A-borrow-checker Area: The borrow checker T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. A-suggestion-diagnostics Area: Suggestions generated by the compiler applied by `cargo fix`. labels Jul 24, 2020
@JohnTitor JohnTitor added the C-enhancement Category: An issue proposing an enhancement or a PR with one. label Jul 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-borrow-checker Area: The borrow checker A-suggestion-diagnostics Area: Suggestions generated by the compiler applied by `cargo fix`. C-enhancement Category: An issue proposing an enhancement or a PR with one. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

2 participants