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

62o28rlo  于 2023-01-13  发布在  其他
关注(0)|答案(1)|浏览(153)

我用这个代码:

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`

你能帮我弄明白吗?

qxgroojn

qxgroojn1#

您可以使用okResult转换为Option。这样您就有了一个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();

相关问题