This question already has an answer here:
- Is there a more idiomatic way to initialize an array with random numbers than a for loop? 1 answer
- What is the proper way to initialize a fixed length array? 2 answers
- How do I generate a vector of random numbers in a range? 2 answers
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