It’s simple, I’d love a function that returns takes a String and returns an Option<String>.
Example implementation:
pub fn none_if_empty(self) -> Option<String> {
if self.is_empty() { None } else { Some(self) }
}
You’re probably asking: “But whyyyyyyyyyyy?”
Honestly I don’t really have a better answer than “Why not?”.
It’s useful when chaining stuff, for example:
if let Some(num) = some_string.iter()
.filter(|c| c.is_digit())
.collect::<String>()
.none_if_empty()
.map(|s| s.parse()) {
println!("Number: {}", num);
}
Problems: What if we then want more functions like this? It could add an unecessary complexity to the string type. Would it be better to have something like .none_if(String::is_empty)? Should it be specific to strings?