I want to be able to convert a Some to a None, if some certain condition holds true for the value within the Some.
For example if I have Some(false) it should be turned into a None, while Some(true) should remain as Some(true)
I found some way to do this.
let value1: Option<bool> = Some(false);
let value2: Option<bool> = Some(true);
let result1 = value1.and_then(|inner| if inner == false { None } else { Some(inner) });
let result2 = value2.and_then(|inner| if inner == false { None } else { Some(inner) });
println!("{:?}", result1); // Prints "None"
println!("{:?}", result2); // Prints "Some(true)"
or even this
let value1: Option<bool> = Some(false);
let value2: Option<bool> = Some(true);
let result1 = if let Some(false) = value1 { None } else { value1 };
let result2 = if let Some(false) = value2 { None } else { value2 };
println!("{:?}", result1); // Prints "None"
println!("{:?}", result2); // Prints "Some(true)"
Looked around the docs’ and I could not find a method that does this in a more succinct way.
Something like
let value = Some(v).to_none_if(predicate)
where value will be None, if predicate is true
or value will remain Some(v) if predicate is false
What will be the most idiomatic way in Rust to do this type of transformation?
>Solution :
What you’re looking for is filter(), although it does the opposite of what you’re asking: it converts to None if the predicate returns false. So you need to negate the expression:
let v = option.filter(|&v| !(v == false));
Or just:
let v = option.filter(|&v| v);