'How to parse an empty string into a None?
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());
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Keenan Thompson |
