How to init a Rust vector with a generator function?

Pretty late to this party, but: resize_with


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


Though @Netwave provides the answer, I'd point to a solution which uses it and provides both more reusability and readability.

  1. Define a generic function, playground:

    fn initialize<T>(count: usize, f: fn(usize) -> T) -> Vec<T> {
        (0..count).map(f).collect()
    }
    
    fn main() {
        let my_vector = initialize(10, |i| i as i32);
        for e in my_vector {
             println!("{}", e);
        }
    }
    
  2. Define a trait, implement it for whatever you want and use it, playground:

    trait Initializer<T> {
        fn initialize(count: usize, f: fn(usize) -> T) -> Vec<T> {
            (0..count).map(f).collect()
        }
    }
    
    impl<T> Initializer<T> for Vec<T> {}
    
    fn main() {
        let my_vector = Vec::initialize(10, |i| i as i32);
        for e in my_vector {
            println!("{}", e);
        }
    }
    

    or more general way:

    trait Initializer<T, U> {
        fn initialize(count: usize, f: fn(usize) -> U) -> T;
    }
    
    impl<T: std::iter::FromIterator<U>, U> Initializer<T, U> for T {
        fn initialize(count: usize, f: fn(usize) -> U) -> T {
            (0..count).map(f).collect::<T>()
        }
    }
    
    fn main() {
        let my_vector = Vec::initialize(10, |i| i as i32);
        for e in my_vector {
            println!("{}", e);
        }
    }
    
  3. Write a macro, playground:

    macro_rules! vec_init {
        ($count: expr, $f: expr) => { (0..$count).map($f).collect() }
    }
    
    fn main() {
        let my_vector: Vec<i32> = vec_init!(10, |i| i as i32);
    }
    

The base still the same is in the @Netwave's answer. You've asked that you want something like:

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

And there is exactly this code in the second item.

Tags:

Rust