Two quick iterator questions

Hi! I have a struct Zone and this initialization:

let zs: Vec<_> = [0;4].iter().map(|_| Zone::default()).collect();
println!("{:?}", zs);

Then, there is struct Block with impl Into<Block> for Zone:

let bs: Vec<Block> = zs.into_iter().map(|x| x.into()).collect();
println!("{:?}", bs);

Both feel unnecessary wordy to me. Please help me improve!

Depending on Zone and Block you have various options.

If Zone is Copy Clone (sry remembered this wrong) you could simply write:

let zs = [Zone::default(); 4].to_vec();

But I think thats not the case. In order to remove one call you could use a Range:

let zs: Vec<_> = (0..4).map(|_| Zone::default()).collect();

For the Block creation you can do what clippy recommends:

let bs: Vec<Block> = zs.into_iter().map(Zone::into).collect();

For the rest I see no sensible reason to remove.


One note: Often it is more ergonomic to implement From rather than Into. First because From automaticly implements Into and second then you could write:

bs: Vec<_> = zs.into_iter().map(Block::from).collect();

But thats just a matter of personal taste.

2 Likes

If Zone is Clone

let zs = vec![Zone::default(); 4];

otherwise

let zs: Vec<_> = std::iter::repeat_with(Zone::default).take(4).collect();

For the second I can only repeat the From recommendation.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.