The title may be a bit confusing, so please check the code:
pub fn generate_random_map(mut commands: Commands) {
let mut rng = XorShiftRng::seed_from_u64(1u64);
commands.spawn_batch(
(-64i32..64i32).flat_map(|x| {
(-64i32..64i32).map(move |y| SpriteBundle {
sprite: Sprite {
color: if rng.gen::<bool>() { //The rng here
Color::rgb(0.0, 1.0, 0.0)
} else {
Color::rgb(0.5, 0.5, 0.0)
},
custom_size: Some(const_vec2!([50.0, 50.0])),
..default()
},
transform: Transform::from_xyz(x as f32 * 50.0, y as f32 * 50.0, 0.0),
..default()
})
})
);
}
The compiler complains:
cannot move out of `rng`, a captured variable in an `FnMut` closure
I also tried collecting the Sprites into a vector beforehand, which didn't work either:
let pre_generated_sprites = (-64i32..64i32)
.flat_map(|x| {
(-64i32..64i32).map(move |y| SpriteBundle {
sprite: Sprite {
color: if rng.gen::<bool>() { //the rng here
Color::rgb(0.0, 1.0, 0.0)
} else {
Color::rgb(0.5, 0.5, 0.0)
},
custom_size: Some(const_vec2!([50.0, 50.0])),
..default()
},
transform: Transform::from_xyz(x as f32 * 50.0, y as f32 * 50.0, 0.0),
..default()
})
})
.collect::<Vec<_>>();
I'm new to Rust, and this code seems legit in languages like Lisp. Do I have to use a nested for
?
I made it work like this:
let mut rng = XorShiftRng::seed_from_u64(1u64);
let mut v = Vec::new();
for x in -64..64 {
for y in -64..64 {
v.push(SpriteBundle {
sprite: Sprite {
color: if rng.gen::<bool>() {
Color::rgb(0.0, 1.0, 0.0)
} else {
Color::rgb(0.5, 0.5, 0.0)
},
custom_size: Some(const_vec2!([50.0, 50.0])),
..default()
},
transform: Transform::from_xyz(x as f32 * 50.0, y as f32 * 50.0, 0.0),
..default()
})
}
}
commands.spawn_batch(v.into_iter());
But that way flat_map
is kind of pointless, and using a Vec
introduces copies, so I'm guessing I did something wrong. How should I structure the code to make it work, elegantly?