Closed
Description
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.