Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to init a Rust vector with a generator function?

Tags:

rust

Hopping between languages can be painful. Idioms of one language "feel good" and one starts to look for the same idioms in other languages.

In F#, there is a way to init an array with the help of a generator function. Array.init n generator. Now, that I hopped to Rust for a little while, I wonder if there is a similar facility in place or if I have to create myself such a facility.

Studying Rust standard library documentation about vectors, I could not find anything similar to what I am looking for.

// Looking for something similar to:
Vec<T>::init(n : usize, generator : F) -> Vec<T> 
    where F: Fn(usize) -> T {
    // ...
}

Maybe it works differently in Rust, by means of iterators. But I must admit, that Rust iterators (and their myriads of flavors) are still a tad foggy to my simple mind.

like image 516
BitTickler Avatar asked Dec 29 '17 10:12

BitTickler


2 Answers

You can use a range withing a map and then collect the results.

Like in the example for F# docs:

let my_vector : Vec<i32> = (1..11).map(|x| x*x).collect();

Check this Playground

like image 112
Netwave Avatar answered Oct 22 '22 09:10

Netwave


Pretty late to this party, but: resize_with

like image 24
Listerone Avatar answered Oct 22 '22 08:10

Listerone