Skip to content

Excessively strict borrowing rules. #15001

@smosher

Description

@smosher
rustc 0.11.0-pre-nightly (7ec7805 2014-06-16 08:16:49 +0000)
host: x86_64-unknown-linux-gnu

I'm not sure if this is intentional with the new borrowing rules, but I don't think it should be. When calling a &mut self method on a struct, you can't pass in a field of the struct by value, nor can you express a computed value in the arguments.

Test case:

struct Foo { x: int }
impl Foo {
    fn set_x(&mut self, new: int) { self.x = new }
}

fn main() { 
    let t = &mut Foo { x: 0 };
    // compiles:
    let tmpx = t.x;
    t.set_x(tmpx + 1);
    // borrow fails:
    t.set_x(t.x + 1)
}

The borrow of t.x fails, claiming that t is already borrowed by t.setx, but I would expect t.x + 1 to be evaluated prior to the mutable borrow (at least conceptually), and to behave essentially like the pair of lines above which compile successfully.

t2.rs:13:11: 13:14 error: cannot use `t.x` because it was mutably borrowed
t2.rs:13                t.set_x(t.x + 1);
                                ^~~
t2.rs:13:3: 13:4 note: borrow of `*t` occurs here
t2.rs:13                t.set_x(t.x + 1);
                        ^
error: aborting due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions