fn increment_value_if_exists(
value: &mut Option<u8>,
) {
if let Some(num) = *value {
value.insert(num + 1);
}
}
fn main() {
let mut foo: Option<u8> = Some(1);
increment_value_if_exists(&mut foo);
println!("{:?}", foo);
let mut bar: Option<u8> = None;
increment_value_if_exists(&mut bar);
println!("{:?}", bar);
}
Which "works", but gives the warning:
warning: unused return value of `Option::<T>::insert` that must be used
--> src/main.rs:5:9
|
5 | value.insert(num + 1);
| ^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_must_use)]` on by default
= note: if you intended to set a value, consider assignment instead
I know that using .insert is wrong (I'm leveraging a side effect), but I can't seem to get the right incantation of dereferencing or unwrapping to successfully increment the value of the Option reference in the function.
I don't consider the version with map as clear as the if let. The map method is lazy in most contexts, and it's purpose is to create a new Option rather than to have a side-effect.