Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse an empty string into a None?

Tags:

rust

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());
like image 249
utx0_ Avatar asked Mar 08 '26 07:03

utx0_


1 Answers

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

  • String::is_empty
  • Option::filter
  • bool::then
like image 153
Sören Avatar answered Mar 09 '26 21:03

Sören



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!