Skip to content

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

Closed
@erickt

Description

@erickt

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions