-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,381
  • 1
  • 11
  • 25
  • 1
    Is _"without using mutable variables"_ an artificial constraint? Creating the array and then doing `for v in &mut w {` or `for v in w.iter_mut()` would appear to be the usual way of doing this. See also: https://stackoverflow.com/q/26185618/1233251 – E_net4 Jul 20 '19 at 15:26
  • 1
    Of course you can limit the mutability to a nested scope: `let w = { let mut array = ...; ...; array };`. – Sven Marnach Jul 20 '19 at 16:05
  • @E_net4 does `for v in &mut w {` work if `w` is not declated as mutable to begin with? – Mark Jul 20 '19 at 19:54
  • it does not without declaring `w` as mutable, thus why I'm asking. – E_net4 Jul 20 '19 at 20:03
  • @E_net4 Yes. I am avoiding using mutable variables. – Listerone Jul 20 '19 at 23:02
  • Possible duplicate of [How do I create and initialize an immutable array?](https://stackoverflow.com/questions/26435046/how-do-i-create-and-initialize-an-immutable-array) – E_net4 Jul 21 '19 at 01:30
  • @E_net4 Not a duplicate. The questions are distinctly different. – Listerone Jul 21 '19 at 15:55
  • What about this one? https://stackoverflow.com/q/26757355/1233251 – E_net4 Jul 21 '19 at 16:42

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
  • 97,764
  • 37
  • 219
  • 309
-1

The answer is NO. ⠀

Listerone
  • 1,381
  • 1
  • 11
  • 25