Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the idiomatic way to convert a Some into a None given a predicate in Rust?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading