It would be nice if Rust\'s Option provided some additional convenience methods like Option#flatten and Option#flat_map, where f
These probably already exist, just as different names to what you expect. Check the docs for Option.
You'll see flat_map more normally as and_then:
let x = Some(1);
let y = x.and_then(|v| Some(v + 1));
The bigger way of doing what you want is to declare a trait with the methods you want, then implement it for Option:
trait MyThings {
fn more_optional(self) -> Option;
}
impl MyThings for Option {
fn more_optional(self) -> Option
For flatten, I'd probably write:
fn flatten(opt: Option
But if you wanted a trait:
trait MyThings {
fn flatten(self) -> Option;
}
impl MyThings for Option
Would there be a way to allow flatten to arbitrary depth
See How do I unwrap an arbitrary number of nested Option types?