【发布时间】:2018-09-22 03:14:24
【问题描述】:
我正在尝试编写一个特征,允许我将多个嵌套的 Option<Option<...<T>>>>“解包”为单个 Option<T>,以便更好地使用我正在使用的 API。我正在尝试创建一个通用解决方案,但我不知道如何使其工作。
这是我的众多尝试之一:
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>`
【问题讨论】:
-
如果你知道有 3 次嵌套,为什么不直接调用
unwrap()链接 3 次呢?fn main() { let x = Some(Some(Some(1))); println!("{:?}", x.unwrap().unwrap().unwrap()); } -
Options 可能在某些时候包含 None。例如:一些(无)或一些(一些(无))。这两个都应该映射到 None。 -
我是 rust 新手,但理解你的意思。谢谢
-
我建议不要将其命名为“unwrap”,因为这通常意味着 Rust 中的“panic on None”,而不是您在此处尝试实现的行为。