gpt4 book ai didi

rust - 如何使用可能失败的函数调用 Iterator .map()?

转载 作者:行者123 更新时间:2023-12-02 17:59:42 24 4
gpt4 key购买 nike

我正在使用此代码:

let players: Vec<Player> = players_to_create
.iter()
.map(|o| Player::new(&o.id, &o.team_id, &o.name)?)
.collect();

但我收到此错误:

error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/main.rs:17:57
|
17 | .map(|o| Player::new(&o.id, &o.team_id, &o.name)?)
| --- ^ cannot use the `?` operator in a closure that returns `Player`
| |
| this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Result<Infallible, ()>>` is not implemented for `Player`

如果我删除 ? 我会收到以下错误:

error[E0277]: a value of type `Vec<Player>` cannot be built from an iterator over elements of type `Result<Player, ()>`
--> src/main.rs:15:32
|
15 | let players: Vec<Player> = players_to_create
| ________________________________^
16 | | .iter()
17 | | .map(|o| Player::new(&o.id, &o.team_id, &o.name))
| |_________________________________________________________^ value of type `Vec<Player>` cannot be built from `std::iter::Iterator<Item=Result<Player, ()>>`
18 | .collect();
| ------- required by a bound introduced by this call
|
= help: the trait `FromIterator<Result<Player, ()>>` is not implemented for `Vec<Player>`
= help: the trait `FromIterator<T>` is implemented for `Vec<T>`
note: required by a bound in `collect`

你能帮我理解一下吗?

最佳答案

您可以使用 ok 转换Result发送至Option s。然后你就有了 Iterator<Item = Option<Player>>可以直接收集到 Option<Vec<Player>> :

players = 
players_to_create
.iter()
.map(|o| Player::new(&o.id, &o.team_id, &o.name).ok())
.collect();

或者您可以更改 player 的类型至Result<Vec<Player>, ???> (将 ??? 替换为实际的错误类型)并直接收集到该错误类型:

let players: Result<Vec<Player>, _> =
players_to_create
.iter()
.map(|o| Player::new(&o.id, &o.team_id, &o.name))
.collect();

关于rust - 如何使用可能失败的函数调用 Iterator .map()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74704140/

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