我用这个代码:
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`
你能帮我弄明白吗?
1条答案
按热度按时间qxgroojn1#
您可以使用
ok
将Result
转换为Option
。这样您就有了一个Iterator<Item = Option<Player>>
,它可以直接收集到Option<Vec<Player>>
中:或者,您可以将
player
的类型更改为Result<Vec<Player>, ???>
(将???
替换为实际的错误类型),并直接收集到该类型: