Cercando di compilazione:Perché unwrap_or() mantiene il prestito in ambito?
fn main() {
let mut vec = vec![1, 2, 3];
let four: &mut u32 = borrow_or_add(&mut vec, 4);
}
fn borrow_or_add(vec: &mut Vec<u32>, val: u32) -> &mut u32 {
vec.iter_mut().find(|v| **v == val).unwrap_or({
vec.push(val);
vec.last_mut().unwrap()
})
}
... ha pronunciato la seguente risultato:
q.rs:8:9: 8:12 error: cannot borrow `*vec` as mutable more than once at a time
q.rs:8 vec.push(val);
^~~
q.rs:7:5: 7:8 note: previous borrow of `*vec` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*vec` until the borrow ends
q.rs:7 vec.iter_mut().find(|v| **v == val).unwrap_or({
^~~
q.rs:12:2: 12:2 note: previous borrow ends here
q.rs:6 fn borrow_or_add(vec: &mut Vec<u32>, val: u32) -> &mut u32 {
...
q.rs:12 }
^
q.rs:10:9: 10:12 error: cannot borrow `*vec` as mutable more than once at a time
q.rs:10 vec.last_mut().unwrap()
^~~
q.rs:7:5: 7:8 note: previous borrow of `*vec` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*vec` until the borrow ends
q.rs:7 vec.iter_mut().find(|v| **v == val).unwrap_or({
^~~
q.rs:12:2: 12:2 note: previous borrow ends here
q.rs:6 fn borrow_or_add(vec: &mut Vec<u32>, val: u32) -> &mut u32 {
...
q.rs:12 }
^
q.rs:10:9: 10:12 error: cannot borrow `*vec` as mutable more than once at a time
q.rs:10 vec.last_mut().unwrap()
^~~
q.rs:7:5: 7:8 note: previous borrow of `*vec` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*vec` until the borrow ends
q.rs:7 vec.iter_mut().find(|v| **v == val).unwrap_or({
^~~
q.rs:12:2: 12:2 note: previous borrow ends here
q.rs:6 fn borrow_or_add(vec: &mut Vec<u32>, val: u32) -> &mut u32 {
...
q.rs:12 }
^
Per quanto ne so, il corpo di unwrap_or()
non può fare riferimento al prestito citato di vec
, quindi, perché non viene eliminato dall'ambito di applicazione? C'è un modo elegante per implementare questa funzione? In realtà non riesco a trovare un modo per eseguire correttamente questa operazione senza utilizzare due passaggi e uno bool
(ad esempio).