Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can even write e.g. this:

  let mut jim: Goat;
  // Potentially much later ...
  if some_reason {
    jim = make_a_new_goat();
  } else {
    jim = get_existing_goat();
  }
  use(jim); // In some way we use that goat now
The compiler can see OK, we eventually initialized this variable before we used it, there's no way we didn't initialize it so that's fine, this compiles.

But, if we screw up and make it unclear whether jim is initialized, probably because in some cases it wouldn't be - that doesn't compile.

This is the usual "avoid early initialization" C++ programmers are often thinking of and it doesn't need MaybeUninit, since it's definitely fine if you're correct, it's just that the C++ compiler is happy (before C++ 26) with just having Undefined Behaviour if you make any mistakes and the Rust compiler will reject that.

[Idiomatically this isn't good Rust, Rust is an expression language so we can just write all that conditional if-else block in the initializer itself and that's nicer, but if you're new to this the above works fine.]




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: