As already mentioned, this is not a mutation, but delayed initialization:
- Mutation
- consists in changing the value of an existing variable,
- deferred initialization is the declaration of a variable at one point and its initialization later.
The Rust compiler keeps track of 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 has been migrated).
The most important reason for using delayed initialization is scope .
fn main() { let x; let mut v = vec!(); { x = 2; v.push(&x); } println!("{:?}", v); }
In Rust, the borrower verifies that the link cannot survive the value to which it refers, preventing broken links.
This means that v.push(&x) requires that x live longer than v , and therefore must be declared before v .
The need for it often does not arise, but when it needs other solutions, a check of the execution time is required.
source share