5

How to initialize an array such that each element is different programmatically (not manually specifying all the elements)?

It seems like there should be some way to do so via closure, for example:

fn main() {
    let x: [u32; 10] = [0; 10];
    println!("{:?}", x);

    let mut count = 0;
    let mut initfn = || { let tmp = count; count += 1; tmp };

    // What I want below is a non-copying array comprehension -- one
    // which runs initfn() 10 times...  Is there such a thing?  Maybe
    // using iterators?
    let y: [u32; 10] = [initfn(); 10];
    println!("{:?}", y);

    // The goal is to avoid the following because my real use case
    // does not allow default values for the array elements...
    let mut z: [usize; 10] = [0; 10];
    for i in 0..10 {
        z[i] = i;
    }
}

update: Can this be done without using "unsafe"?

There is a macro-based answer by erikt from more than a year ago which looks promising, but relies on iterative anti-quote expansion by the macro system that does not seem to exist... Has the language changed to make this possible now?

2
  • let y: [u32; 10] = [initfn(),initfn(),initfn(),initfn(),initfn(),initfn(),initfn(),initfn(),initfn(),initfn()];. Commented Apr 16, 2015 at 20:23
  • let x: Cow<[u32]> = Cow::from_iter ((0..10) .map (|idx| idx * 2)) looked promising, but it uses a Vec under covers. Commented Apr 18, 2015 at 12:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.