0

I am learning Rust and I find that it does not allow variables to be left uninitialized when they are declared. Question is, I am trying to load input into an array but I don't want to initialize it because the size of the array may be rather large and I think initializing it with some temp value is not good. Currently, this piece of code does not pass the compilation:

let mut height: [u8; maxn];
let mut i = 1; // I want to start from 1, not 0, but this is not the main problem.
while i <= n {
    height[i] = s_it.next().unwrap().parse().unwrap();
    i += 1;
}

So, is there any way I can use?

mcarton
  • 27,633
  • 5
  • 85
  • 95
Fifnmar
  • 372
  • 1
  • 5
  • 9
  • 3
    If the vector is large enough that you wouldn't want to 0-initialize it, you probably don't want it on the stack anyway: Use `Vec`. – mcarton Dec 27 '19 at 13:13
  • Also "it does not allow variables to be left uninitialized when they are declared" is not true. It's perfectly fine not to initialize a variable as long as the compiler can prove that it has always been initialized once before reading it. This is similar to, eg. how C# treats variables and is definitely not just a Rust thing. – mcarton Dec 27 '19 at 13:15

0 Answers0