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

Early returns can cause borrows to last until the end of a function #30223

Closed
ferrugo opened this issue Dec 5, 2015 · 1 comment
Closed

Early returns can cause borrows to last until the end of a function #30223

ferrugo opened this issue Dec 5, 2015 · 1 comment

Comments

@ferrugo
Copy link

ferrugo commented Dec 5, 2015

If a borrowed value is used in a match statement and returned in a match arm, the borrow ends at the end of the function.
The following code illustrates this behaviour:

fn foo(x : &mut Result<usize, usize>) -> &mut usize {
    match x.as_mut() {
        Ok(_) => {},
        Err(m) => {return m;}
    }
    x.as_mut().unwrap()
}

fn main() {
    let mut x = Ok(1);
    foo(&mut x);
}

When I try to compile it, the compiler outputs this message:

test.rs:6:2: 6:3 error: cannot borrow `*x` as mutable more than once at a time
test.rs:6   x.as_mut().unwrap()
            ^
test.rs:2:8: 2:9 note: previous borrow of `*x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*x` until the borrow ends
test.rs:2   match x.as_mut() {
                  ^
test.rs:7:2: 7:2 note: previous borrow ends here
test.rs:1 fn foo(x : &mut Result<usize, usize>) -> &mut usize {
...
test.rs:7 }
          ^
error: aborting due to previous error

(However, the code compiles if the return statement is removed.)

I think the borrow checker is too restrictive in this case, since the borrow of x in line 2 should end in line 5.

I used the following compiler version:

`rustc --version --verbose`:
rustc 1.4.0 (8ab8581f6 2015-10-27)
binary: rustc
commit-hash: 8ab8581f6921bc7a8e3fa4defffd2814372dcb15
commit-date: 2015-10-27
host: x86_64-unknown-linux-gnu
release: 1.4.0
@alexcrichton
Copy link
Member

Thanks for the report! This is a feature known as "non lexical borrows" for us, and that's being tracked over at rust-lang/rfcs#811 so I'm gonna close this in favor of that.

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