0

I want to declare an Array and want to initialize it like this (maybe it is not good in real development, but I just want to figure it out)

the key point is that: 1. h is immutable 2. assign(also initialize) h[0] h[1] and h[2] separately.

use std::thread;
use std::time::Duration;
use rand::Rng; // 0.6.5

fn main() {
    loop {
        let h: [u32; 3];
        h[0] = rand::thread_rng().gen_range(1, 101);
        h[1] = rand::thread_rng().gen_range(1, 101);
        h[2] = rand::thread_rng().gen_range(1, 101);
        println!("{:?}", h);
        thread::sleep(Duration::from_secs(2));
    }
}

but the compiler says that

error[E0381]: use of possibly uninitialized variable: `h`
  --> src\main.rs:11:9
   |
11 |         h[0] = rand::thread_rng().gen_range(1, 101);
   |         ^^^^ use of possibly uninitialized `h`

error: aborting due to previous error

of course h is uninitialized here, so what could I do? or it is impossible to do such a thing

Seact
  • 711
  • 1
  • 5
  • 10
  • https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=def7c91bd7335dbfe36e01c4f28b5984 – Boiethios Mar 13 '19 at 13:29
  • Also see: https://doc.rust-lang.org/book/ch03-02-data-types.html#the-array-type – hellow Mar 13 '19 at 13:35
  • @hellow I didnt describe the problem well. but what if I want to initialize the elements of the array separately? – Seact Mar 13 '19 at 14:02
  • @Seact please do a [mcve] that describe better your problem so. – Stargateur Mar 13 '19 at 14:12
  • @Seact that's covered by multiple of the answers in [the linked duplicate](https://stackoverflow.com/questions/31360993/what-is-the-proper-way-to-initialize-a-fixed-length-array). – Shepmaster Mar 13 '19 at 14:19

0 Answers0