-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.

8
  • 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: stackoverflow.com/q/26185618/1233251 Commented Jul 20, 2019 at 15:26
  • 1
    Of course you can limit the mutability to a nested scope: let w = { let mut array = ...; ...; array };. Commented Jul 20, 2019 at 16:05
  • @E_net4 does for v in &mut w { work if w is not declated as mutable to begin with? Commented Jul 20, 2019 at 19:54
  • it does not without declaring w as mutable, thus why I'm asking. Commented Jul 20, 2019 at 20:03
  • @E_net4 Yes. I am avoiding using mutable variables. Commented Jul 20, 2019 at 23:02

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can create an immutable variable whose value is a &mut [T; N]:

pub fn main() {
    let a = &mut [1, 2, 3];
    a[0] = 42;
    println!("{:?}", a);
    // a = &mut [1; 3]; // error[E0384]: cannot assign twice to immutable variable `a`
    print_type_of(&a); // &mut [i32; 3]
}

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

Comments

-1

The answer is NO. ⠀

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.