-1

If I wanted to populate a list of numbers, I can use a vector, and hence the heap, by doing this:

let w = (0..1024).collect::<Vec<_>>();

But, if I wanted to avoid the heap I have to use an array. To use an array, I have to use a loop which means I must have a mutable variable:

let mut w = [0u32; 1024];
for i in 0..1024 {
    w[i] = i as u32;
}

Is it possible to populate an array without using mutable variables?


This question has been flagged as a dup. I'm not sure how this can possibly be confused.

"How to populate an array without using mut?" means how do I populate an array without using a mutable variable to do so. Any mut, not just the array variable itself.

"How do I create and initialize an immutable array?" means how do I create an immutable array.

Listerone
  • 1,219
  • 6
  • 20

2 Answers2

0

You can't.

Iterator can't guarantee any specific length at compile time, so .collect() can't produce fixed-size arrays.

You can do:

let w = w;

to recreate the binding as immutable afterwards, or move the initialization to a helper function.

Kornel
  • 94,425
  • 32
  • 211
  • 296
-1

The answer is NO. ⠀

Listerone
  • 1,219
  • 6
  • 20