user1002430
user1002430

Reputation:

How to implement iter.collect::<Vec<Vec<_>>>()?

Iterator::collect can transform iterators into so many different structures. So, I was expecting that the following would just work:

let it = (1..5).map(|x| (x..5));
let xss = it.collect::<Vec<Vec<_>>>();
// let xss = it.map(|xs| xs.collect::<Vec<_>>()).collect::<Vec<_>>(); // clunky 

No luck, unfortunately. How can such functionality be implemented?

Upvotes: 0

Views: 111

Answers (1)

jthulhu
jthulhu

Reputation: 8668

What you need is a two-step procedure. First, you should create an iterator of Vec<_>, then collect it.

let it = (1..5).map(|x| (x..5).collect());
let xss = it.collect::<Vec<Vec<_>>>();

See the playground.


Alternatively, if you can't modify right away the iterator:

let it = (1..5).map(|x| (x..5));
let xss = it.map(|x| x.collect()).collect::<Vec<Vec<_>>>();

Upvotes: 2

Related Questions