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

Borrowing from a vec after mutation requires a helper function to compile #4863

Closed
erickt opened this issue Feb 9, 2013 · 1 comment
Closed
Labels
A-lifetimes Area: Lifetimes / regions A-type-system Area: Type system

Comments

@erickt
Copy link
Contributor

erickt commented Feb 9, 2013

I was working on adding a find_or_insert function to the hashmaps, and I ran into some trouble with the lifetime borrow checker. Here's my distilled code:

struct Bucket {
    value: uint,
}

struct A {
    xs: ~[Option<Bucket>],
}

impl A {
    fn find_or_insert1(&mut self, key: uint, value: uint) -> &self/uint {
        match self.xs[key] {
            Some(_) => (),
            None => { self.xs[key] = Some(Bucket { value: value }); }
        }

        match self.xs[key] {
            Some(ref bkt) => &bkt.value,
            None => die!(),
        }
    }

    fn find_or_insert_internal(&mut self, key: uint, value: uint) {
        match self.xs[key] {
            Some(_) => (),
            None => { self.xs[key] = Some(Bucket { value: value }); }
        }
    }

    fn find_or_insert2(&mut self, key: uint, value: uint) -> &self/uint {
        self.find_or_insert_internal(key, value);

        match self.xs[key] {
            Some(ref bkt) => &bkt.value,
            None => die!(),
        }
    }
}

fn main() { }

This errors with:

test.rs:13:22: 13:33 error: assigning to mutable vec content prohibited due to outstanding loan
test.rs:13             None => { self.xs[key] = Some(Bucket { value: value }); }
                                 ^~~~~~~~~~~
test.rs:16:14: 16:25 note: loan of mutable vec content granted here
test.rs:16         match self.xs[key] {
                         ^~~~~~~~~~~
error: aborting due to previous error

However, if instead I comment out find_or_insert1, it compiles fine. It would be great if there was a way to do this in one function, instead of needing a helper function work around lifetime issues.

@nikomatsakis
Copy link
Contributor

I'm pretty sure this is a dup of #4903

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lifetimes Area: Lifetimes / regions A-type-system Area: Type system
Projects
None yet
Development

No branches or pull requests

2 participants