Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to fill a Rust vector with objects using higher order function

I can create a Rust vector and fill it with struct instances using a loop, but I was wondering if I could get the same result using one of the higher order functions like map or such.

Here is some code that works:

#[derive(Debug)]
pub struct sim {
    id: i32,
}

impl Default for sim {
    fn default() -> sim {
        sim { id: 4 }
    }
}

fn main() {
    let mut v2 = Vec::<sim>::new();
    for i in 0..7 {
        v2.push(sim::default())
    }
    println!("{:?}", v2);
}

I tried the code below, but it did not work.

let mut v3 = Vec::<sim>::new();
(0..7).map(|| v3.push(sim::default()));
like image 728
krishnab Avatar asked Feb 03 '26 15:02

krishnab


1 Answers

Your immediate problem is: that isn't how map works at all. Mapping involves taking a sequence and transforming each element in said sequence, producing a new sequence. You should not be using it to just execute side effects for two reasons:

  1. No one is going to expect you to do that, so your code will be more confusing than it should be to anyone else reading it.

  2. Iterators in Rust are lazily computed, meaning that unless you consume the mapped iterator, nothing will happen.

If you really want to do something 7 times, just use a loop. That's what they're for. If you really, desperately need to do something like this, the itertools crate has a foreach method that does this whilst still communicating what's going on.

As to how to actually construct the collection using higher order functions...

#[derive(Clone, Debug)]
pub struct Sim {
    id: i32,
}

impl Default for Sim {
    fn default() -> Sim {
        Sim { id: 4 }
    }
}

fn main() {
    use std::iter;

    let v1 = vec![Sim::default(); 7];
    let v2: Vec<_> = iter::repeat(Sim::default()).take(7).collect();
    let v3: Vec<_> = (0..7).map(|_| Sim::default()).collect();
    let v4: Vec<_> = iter::once(Sim::default()).cycle().take(7).collect();
}

There are probably more. Note that v1, v2, and v4 require the item type to be Clone so that it can make copies.

like image 95
DK. Avatar answered Feb 05 '26 07:02

DK.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!