Is there a way to not have to initialize arrays tw

2019-01-12 04:05发布

问题:

I need to initialize each element of an array to a non-constant expression. Can I do that without having to first initialize each element of the array to some meaningless expression? Here's an example of what I'd like to be able to do:

fn foo(xs: &[i32; 1000]) {
    let mut ys: [i32; 1000];

    for (x, y) in xs.iter().zip(ys.iter_mut()) {
        *y = *x / 3;
    }
    // ...
}

This code gives the compile-time error:

error[E0381]: use of possibly uninitialized variable: `ys`
 --> src/main.rs:5:37
  |
5 |         for (x, y) in xs.iter().zip(ys.iter_mut()) {
  |                                     ^^ use of possibly uninitialized `ys`

To fix the problem I need to change the first line of the function to initialize the elements of ys with some dummy values like so:

let mut ys: [i32; 1000] = [0; 1000];

Is there any way to omit that extra initialization? Wrapping everything in an unsafe block doesn't seem to make any difference.

回答1:

Use std::mem::uninitialized:

let mut ys: [i32; 1000] = unsafe { std::mem::uninitialized() };

This is unsafe because accessing uninitialized values is undefined behavior in Rust and the compiler can no longer guarantee that every value of ys will be initialized before it is read.

You cannot collect into an array, but if you had a Vec instead, you could do:

let ys: Vec<_> = xs.iter().map(|&x| x / 3).collect();

For your specific problem, you could also clone the incoming array and then mutate it:

let mut ys = xs.clone();
for y in ys.iter_mut() { *y = *y / 3 }