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

标签 rust iterator

我正在使用此代码:

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/

相关文章:

string - 如何从 Rust 中的文字创建格式化字符串?

java - 在我的 "Custom Set"实现中需要帮助

c# - C#迭代器中的递归

python - hasattr(obj, '__iter__') 与集合

rust - 如何将 float 转换为字符串?

rust - 借用对结构中属性的引用

rust - 在Rust中检查路径组件的权限

rust - std::process,带有来自缓冲区的 stdin 和 stdout

c++ - 为什么编译器会出现此模板的作用域问题?

c++ - 无法遍历模板列表 C++