I have a function test1
that takes an Option<&mut>
param. The idea is to then pass that param onto other function calls test2
to collect data.
The problem is that the first calls of test2
transfers ownership and so the second call won't compile.
I understand how this can be a problem with a generic type, but since the Option is holding a &mut
I think there must be a clean way to do this?
The best I can manage is:
fn test1(param: Option<&mut usize>) {
if let Some(p) = param {
test2(Some(p));
test2(Some(p));
} else {
test2(None);
test2(None);
}
}
But that's a mess of duplication... must be a better way?
Here's setup I'm working with:
fn main() {
let mut i = 0;
let o_i = Some(&mut i);
test1(o_i);
println!("{}", i);
}
fn test1(param: Option<&mut usize>) {
test2(param);
test2(param);
}
fn test2(param: Option<&mut usize>) {
if let Some(i) = param {
*i += 1;
}
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0382]: use of moved value: `param`
--> src/main.rs:10:11
|
8 | fn test1(param: Option<&mut usize>) {
| ----- move occurs because `param` has type `std::option::Option<&mut usize>`, which does not implement the `Copy` trait
9 | test2(param);
| ----- value moved here
10 | test2(param);
| ^^^^^ value used here after move
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.