I installed Rust 1.13 and tried:
fn main() {
let x: u32;
x = 10; // no error?
}
When I compiled this file there's some warnings, but there's no error. As I'm not declaring x
as mut
, shouldn't x = 10;
cause an error?
I installed Rust 1.13 and tried:
fn main() {
let x: u32;
x = 10; // no error?
}
When I compiled this file there's some warnings, but there's no error. As I'm not declaring x
as mut
, shouldn't x = 10;
cause an error?
As mentioned, this is not mutation, but deferred initialization:
The Rust compiler tracks whether a variable has a value at compile-time, so unlike C there is no risk of accidentally using an uninitialized variable (or unlike C++, a variable that was moved from).
The most important reason for using deferred initialization is scope.
In Rust, the borrow-checker will validate that a reference cannot outlive the value it refers to, preventing dangling references.
This means that
v.push(&x)
requires thatx
lives longer thanv
, and therefore be declared beforev
.The need for it does not crop up often, but when it does other solutions would require run-time checks.
What you have written is identical to:
The compiler will not permit you to mutate it thereafter:
Note that it is a compiler error if you try to use an uninitialized variable:
This feature can be pretty useful if you want to initialize the variable differently based on runtime conditions. A naive example:
But still it will still be an error if there is a possibility that it isn't initialized: