问题
I have a struct containing a 2D array:
struct Block;
struct World {
blocks: [[Block; 10]; 10],
}
How could I write a function which returns an iterator over a 2D array, but with the enumeration indices included?
fn enumerate_blocks(&self) -> impl Iterator<Item = (usize, usize, &Block)>
I managed to write an implementation of the function which just returns an iterator without enumeration indices:
fn blocks(&self) -> impl Iterator<Item = &Block> {
self.blocks.iter().flat_map(|x| x.iter())
}
If I call Iterator::enumerate once, I will get an iterator over (usize, [B; 10])
s. What I can do next to get an iterator over (usize, usize, B)
s?
I know I could make the function return a custom struct then implement Iterator
, like image
does, but ideally I would like to avoid this.
回答1:
If I call
Iterator::enumerate
once, I will get an iterator over(usize, [B; 10])
s. What I can do next to get an iterator over(usize, usize, B)
s?
Call Iterator::enumerate on the inner array in the same way, continuing to use Iterator::flat_map to combine them. Use Iterator::map to add the outer index to the inner tuple.
#[derive(Debug, Default)]
struct Block;
#[derive(Debug, Default)]
struct World {
blocks: [[Block; 2]; 3],
}
impl World {
fn blocks(&self) -> impl Iterator<Item = (usize, usize, &Block)> {
self.blocks
.iter()
.enumerate()
.flat_map(|(x, v)| v.iter().enumerate().map(move |(y, v)| (x, y, v)))
}
}
fn main() {
let w = World::default();
for (x, y, v) in w.blocks() {
println!("{}, {}, {:?}", x, y, v)
}
}
0, 0, Block
0, 1, Block
1, 0, Block
1, 1, Block
2, 0, Block
2, 1, Block
来源:https://stackoverflow.com/questions/52339851/how-do-i-return-an-iterator-over-a-2d-array-with-the-enumeration-indices-include