Since it's possible to pass a mutable reference to a vector around (without causing moves), how can an Option<reference>
be passed to functions multiple times without causing borrow checking errors?
This simple example just shows what happens when an Option<&mut Vec<usize>>
is passed multiple times to a function:
fn maybe_push(mut v_option: Option<&mut Vec<usize>>) -> usize {
let mut c = 0;
if let Some(ref mut v) = v_option.as_mut() {
for i in 0..10 {
v.push(i);
c += i;
}
}
return c;
}
fn maybe_push_multi(v_option: Option<&mut Vec<usize>>) -> usize {
let mut c = 0;
c += maybe_push(v_option);
c += maybe_push(v_option);
c += maybe_push(None);
return c;
}
fn main() {
let mut v: Vec<usize> = vec![];
let v_option = Some(&mut v);
println!("{}", maybe_push_multi(v_option));
}
Gives the error:
error[E0382]: use of moved value: `v_option`
--> <anon>:17:21
|
16 | c += maybe_push(v_option);
| -------- value moved here
17 | c += maybe_push(v_option);
| ^^^^^^^^ value used here after move
|
= note: move occurs because `v_option` has type `std::option::Option<&mut std::vec::Vec<usize>>`, which does not implement the `Copy` trait