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

Borrow check thinks that a method call starts before its parameters are evaluated #10397

Closed
MicahChalmer opened this issue Nov 10, 2013 · 1 comment

Comments

@MicahChalmer
Copy link
Contributor

When you call a method with a borrowed self, the compiler appears to assume that the borrow of self starts before the other parameters to that method have been evaluated, which seems wrong. This forces you to create local variables unnecessarily. Here's an example of code that I think should compile, but doesn't:

struct Thingy {
    i:int
}
impl Thingy {
    fn do_something_mutable(&mut self, x: int) {
        // Just assume there's a real reason for self to be mutable here...
        println(format!("{}", x));
    }
    fn get_i(&self) -> int { self.i }
}

fn main() {
    let mut o = Thingy{ i: 2 };
    o.do_something_mutable(o.get_i());  // This line should compile, but doesn't
}

the error is this:

lifetime-call-param.rs:13:27: 13:28 error: cannot borrow `o` as immutable because it is also borrowed as mutable
lifetime-call-param.rs:13     o.do_something_mutable(o.get_i());
                                                     ^
lifetime-call-param.rs:13:4: 13:5 note: second borrow of `o` occurs here
lifetime-call-param.rs:13     o.do_something_mutable(o.get_i());
                              ^

If you replace the problematic line with this it compiles and works fine:

let y = o.get_i();
o.do_something_mutable(y);

but isn't that equivalent to the non-compiling version?

@huonw
Copy link
Member

huonw commented Nov 10, 2013

You are correct that this is a bug (in fact, a duplicate of #6268).

Moving the inner call out into a temporary is the recommended fix.

(Random comment: using println!("{}", x) will be marginally higher performance than println(format!(...)) (and it looks neater), since the former can effectively write straight to stdout, while the latter has to write to an allocated string and then write the string to stdout.)

@huonw huonw closed this as completed Nov 10, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants