如何解开任意数量的嵌套Option类型? [英] How do I unwrap an arbitrary number of nested Option types?
问题描述
我正在尝试编写一个特征,该特征将允许我将多个嵌套的Option<Option<...<T>>>>
解包"到单个Option<T>
以便更好地使用我正在使用的API.我正在尝试创建一个通用的解决方案,但我不知道如何使它工作.
I'm trying to write a trait that will allow me to "unwrap" multiple nested Option<Option<...<T>>>>
to a single Option<T>
to better work with an API I am using. I'm trying to create a generic solution, but I can't figure out how to make it work.
这是我的许多尝试之一:
This is one of my many attempts:
trait UnwrapOption<T> {
fn unwrap_opt(self) -> Option<T>;
}
impl<T> UnwrapOption<T> for Option<T> {
fn unwrap_opt(self) -> Option<T> {
self
}
}
impl<T> UnwrapOption<T> for Option<Option<T>> {
fn unwrap_opt(self) -> Option<T> {
match self {
Some(e) => e.unwrap_opt(),
None => None,
}
}
}
fn main() {
let x = Some(Some(Some(1)));
println!("{:?}", x.unwrap_opt());
}
推荐答案
如其他答案所示,不是扁平化嵌套选项,我建议您不要创建首先需要变平的Option<Option<T>>
.在我见过的大多数情况下,这是因为有人在应该使用Option::and_then
的情况下误用了Option::map
:
Instead of flattening out the nested option, as the other answer shows, I'd advocate that you never create an Option<Option<T>>
that you need to flatten in the first place. In the majority of cases I've seen, it's because someone misuses Option::map
when they should have used Option::and_then
:
fn main() {
let input = user_input();
let a = input.map(add1);
// a is Option<Option<i32>>
let b = input.and_then(add1);
// a is Option<i32>
}
fn user_input() -> Option<i32> {
Some(10)
}
fn add1(a: i32) -> Option<i32> {
Some(a + 1)
}
请记住,Rust是一种静态类型的语言;您将永远知道嵌套的确切级别.
Remember that Rust is a statically typed language; you will always know the exact level of nesting.
另请参阅:
这篇关于如何解开任意数量的嵌套Option类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!