Creating a vector via an iterator

Another way to create a vector is via an iterator. This is achieved via the collect() method:

let my_vec: Vec<u64> = (0..10).collect(); 
The format for the iterator is very convenient. Instead of the likes of let foo = {0,1,2,3};, this is shortened to use .., which means all numbers between a and b (b being excluded - so 0 .. 10 creates a vector containing 0,1,2,3,4,5,6,7,8,9). This can be seen in the source example supplied with this book.

Get Learning Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.