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?