gpt4 book ai didi

generics - 如何打开任意数量的嵌套选项类型?

转载 作者:行者123 更新时间:2023-11-29 07:47:26 24 4
gpt4 key购买 nike

我正在尝试编写一个允许我“展开”多个嵌套 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>`

最佳答案

而不是展平嵌套选项,因为 other answer shows ,我建议您永远不要创建 Option<Option<T>>你首先需要弄平。在我见过的大多数情况下,这是因为有人误用了 Option::map当他们应该使用 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 是一种静态类型语言;您将始终知道确切的嵌套级别。

另见:

关于generics - 如何打开任意数量的嵌套选项类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52453180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com