Given a collection (vector/slice) of structs. How do I create a combined iterator over some fields in each struct?
Below is a concrete attempt using flat_map
:
struct Game {
home_team: u8,
away_team: u8,
}
fn teams(games: &[Game]) -> impl Iterator<Item = u8> {
games
.iter()
.flat_map(|game| [game.home_team, game.away_team].iter().map(|x| x.clone()))
}
fn main() {
let data = &[
Game {
home_team: 1,
away_team: 2,
},
Game {
home_team: 1,
away_team: 3,
},
];
let non_unique_teams: Vec<u8> = teams(data).collect();
}
My actual use-case is very similar. In particular, the fields that form the basis of the iterator implements Copy
, making cloning perfectly fine.
My intuition tells me that this should work since I'm cloning the only things I need to "take" from the incoming slice. Obviously, my understanding of the borrow checker is to poor for me to grasp this.