Array initialization using default Foo struct

Viewed 65

Any help here would be greatly appreciated.

The rust code below populates an array with default Foo values, up to N elements. I wish to do the same thing without having to explicitly code the Foo elements. That would obviously be unreasonable for large values of N (1K to 1M, or even more).

My primary goal is speed so I wish to avoid using vectors.

Also, I would like to avoid unsafe code blocks. If I must use unsafe, then the simpler the better for obvious reasons. ( I tend to think that if unsafe is required, then it should be a very high priority call for an improvement to rust-lang to change this. Therefore I would like the code easily modified to take advantage of such a hypothetical future version of rust. )

Again, I really appreciate experienced input here. If this is indeed a problem area in the language I think the answer(s) provided here would be very important to pin down. If there are references or links then please share!

struct Foo {
    abc: String,
    def: u32,
}

const N : usize = 2;

fn main() {
    let foo: [Foo; N] = [
        Foo{
            abc: "default".to_string(),
            def: 0,
        },
        Foo{
            abc: "default".to_string(),
            def: 0,
        },
    ];
    
    for bar in foo.iter() {
        println!("bar.abc={}, bar.def={}", bar.abc, bar.def);
    }
}
0 Answers
Related