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

Can't call &mut method inside expression used as argument for a &mut method of the same struct #88167

Closed
JakubKoralewski opened this issue Aug 19, 2021 · 4 comments
Labels
C-bug Category: This is a bug.

Comments

@JakubKoralewski
Copy link

I tried this code:

fn main() {
    struct Xd;
    impl Xd {
        fn x(&mut self, y: &str) {println!("{}", y)}
    }
    let mut xd = Xd;
    xd.x(match "x" {
        "x" => {
            xd.x("x");
            "x"
        },
        _ => "y"
    })
}

I expected to see this happen: print x twice

Instead, this happened:

   Compiling playground v0.0.1 (/playground)
error[E0499]: cannot borrow `xd` as mutable more than once at a time
 --> src/main.rs:9:13
  |
7 |     xd.x(match "x" {
  |     -- - first borrow later used by call
  |     |
  |     first mutable borrow occurs here
8 |         "x" => {
9 |             xd.x("x");
  |             ^^ second mutable borrow occurs here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0499`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

Meta

rustc --version --verbose:

1.54.0
@JakubKoralewski JakubKoralewski added the C-bug Category: This is a bug. label Aug 19, 2021
@jonas-schievink
Copy link
Contributor

This is working as intended. Method receivers are evaluated before arguments, so the outer function call already borrows xd when the second call is evaluated.

cc #49434

@JakubKoralewski
Copy link
Author

Thanks. Why is this the intended behavior though?

@jonas-schievink
Copy link
Contributor

Because the receiver is intentionally evaluated before arguments

@JakubKoralewski
Copy link
Author

JakubKoralewski commented Aug 20, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: This is a bug.
Projects
None yet
Development

No branches or pull requests

2 participants