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

Confusing compiler error with auto-deref on a type without DerefMut to call a function requiring &mut self #57839

Closed
sdroege opened this issue Jan 22, 2019 · 1 comment · Fixed by #62468
Labels
A-diagnostics Area: Messages for errors, warnings, and lints

Comments

@sdroege
Copy link
Contributor

sdroege commented Jan 22, 2019

This seems to be slightly related to #28419 but maybe not the same as the error is a different? Feel free to close if it actually is the same.

use std::ops;

struct Foo(Bar);

struct Bar;

impl ops::Deref for Foo {
    type Target = Bar;
    fn deref(&self) -> &Bar {
        &self.0
    }
}

impl Bar {
    fn do_stuff(&mut self) {}
}

fn main() {
    let mut f = Foo(Bar);
    f.do_stuff();
}

This currently gives the following error

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/main.rs:20:5
   |
20 |     f.do_stuff();
   |     ^ cannot borrow as mutable

error: aborting due to previous error

There are multiple problems with that error message:
a) A DerefMut impl would be needed but that's not what it writes
b) It's unclear where the & reference in that line comes from (auto-deref!)
c) f itself can actually be borrowed mutable, but the error suggests that it can't and that this is the problem

Maybe there's some opportunity for generally improving error messages when auto-deref is involved, and somehow making that clear in the error message. E.g. by putting another paragraph there saying when calling do_stuff() on type Foo caused by auto-deref or similar, or maybe similar to how borrow errors are shown ("which was borrowed mutable $here") by marking in a separate message that auto-deref has happened here.

@sdroege
Copy link
Contributor Author

sdroege commented Jan 23, 2019

For some context, you could imagine Foo to be Arc / Rc but the problem is not specific to those two :)

@Centril Centril added the A-diagnostics Area: Messages for errors, warnings, and lints label Jan 24, 2019
bors added a commit that referenced this issue Jul 13, 2019
…bank

Improve diagnostics for invalid mutation through overloaded operators

Closes #58864
Closes #52941
Closes #57839
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants