The loan is active, at least for the entire application. Unfortunately, the usual solution to pulling Option into a separate statement will not help, since it will still contain a mutable link (in Some ), which forces the vector to also expand. This seems inevitable when using find() . The compiler is concerned that the pointer to the Vector repository is floating somewhere and might be invalid by clicking on the vector (which could lead to redistribution). This includes not only the pointer in the returned Option , but also those that can be made inside one of these functions. This would be a very urgent problem, if not for the fact that there are no "hidden" pointers, and you only click when Option not a pointer. The life cycle system is not good enough to capture this fact, and I see no easy way to fix it or get around it.
What you can do is use position to find the index:
fn borrow_or_add(vec: &mut Vec<u32>, val: u32) -> &mut u32 { match vec.iter().position(|&v| v == val) { Some(i) => &mut vec[i], None => { vec.push(val); vec.last_mut().unwrap() } } }
Note that indexes in vectors are essentially distinguished pointers. They may start to refer to the wrong element if the vector changes, although they cannot become dangling when redistributing, and invalid indices (larger than the largest valid index) will cause panic, not memory. However, getting the index from position , and then indexing it, is true only because the vector does not change (substantially) between them.
source share