What is the idiomatic way to handle the parsing of an empty string into a None and not a Some("")?
let handle: Option<String> = x.get(0).and_then(|v| v.parse().ok());
If you start with a String:
let string = String::new();
let handle = Some(string).filter(|s| !s.is_empty());
Since Rust 1.50 you can also use bool::then (thanks sebpuetz)
let handle = string.is_empty().not().then(|| string);
// or
let handle = (!string.is_empty()).then(|| string);
With your code:
let handle = x.get(0)
.and_then(|v| v.parse().ok())
.filter(String::is_empty);
Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With