rust - How to pass `Option<&mut ...>` to multiple function calls without causing move errors? -
since it's possible pass mutable reference vector around (without causing moves), how can option<reference>
passed functions multiple times without causing borrow checking errors?
this simple example shows happens when option<&mut vec<usize>>
passed multiple times 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() { 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 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>>`, not implement `copy` trait
you can pass option
reference too, if don't want moved function.
fn maybe_push(mut v_option: &mut option<&mut vec<usize>>) -> usize // ... maybe_push_twice(&mut v_option);
then replace:
maybe_push(none);
with:
maybe_push(&mut none);
Comments
Post a Comment