2

I'm using this code:

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

but I'm geting this error:

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` 

If I remove the ? I get the following error:

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` 

Can you help me understand?

1 Answer 1

5

You can use ok to convert the Results to Options. Then you have an Iterator<Item = Option<Player>> which can be collected directly into an Option<Vec<Player>>:

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

Or you can change the type of player to Result<Vec<Player>, ???> (replacing ??? with the actual error type) and collect directly to that instead:

let players: Result<Vec<Player>, _> = players_to_create .iter() .map(|o| Player::new(&o.id, &o.team_id, &o.name)) .collect(); 
Sign up to request clarification or add additional context in comments.

1 Comment

One subtle detail to be aware of: using collect in this way short-circuits, so it will stop iterating after the first Err/None.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.