Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization for non-copyable type

I want to be able to do this:

let mut my_array: [MyType; 10] = [MyType::new(1, 2, 3, 4); 10];

when MyType isn't copyable, i.e. I want it to call the constructor for each element rather than calling it once and trying to copy. Is this possible?

Is it also possible to include the array index in the constructor call:

let mut my_array: [MyType; 10] = [MyType::new(_index, 2, 3, 4); 10];

so that my array is initialized with MyType:new(1,2,3,4), MyType:new(2,2,3,4), MyType:new(3,2,3,4), etc.

like image 974
Pete Fordham Avatar asked Mar 24 '26 14:03

Pete Fordham


1 Answers

The array-init library provides a safe interface to do this:

let mut my_array: [MyType; 10] = array_init(|i| MyType::new(i, 2, 3, 4));
like image 68
Challenger5 Avatar answered Mar 27 '26 04:03

Challenger5



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!