我正在try 写一个特性,它允许我将多个嵌套的Option<Option<...<T>>>>
"展开"到单个Option<T>
,以便更好地使用我正在使用的API.我正在try 创建一个通用的解决方案,但我不知道如何使其工作.
这是我的许多try 之一:
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());
}
error[E0282]: type annotations needed
--> src/main.rs:22:24
|
22 | println!("{:?}", x.unwrap_opt());
| --^^^^^^^^^^--
| | |
| | cannot infer type for type parameter `T` declared on the trait `UnwrapOption`
| this method call resolves to `Option<T>`