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.
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
Pretty late to this party, but: resize_with
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With