Why does the compiler not report an error when changing a variable that is not declared as mutable?

I installed Rust 1.13 and tried:

fn main() { let x: u32; x = 10; // no error? } 

When I compiled this file there are some warnings, but there are no errors. Since I do not declare x as mut , should not x = 10; cause an error?

+5
source share
2 answers

What you wrote is identical:

 let x: u32 = 10; 

The compiler will not allow you to mutate it later:

 let x: u32; x = 10; x = 0; // Error: re-assignment of immutable variable `x` 

Note that this is a compiler error if you are trying to use an uninitialized variable:

 let x: u32; println!("{}", x); // Error: use of possibly uninitialized variable: `x` 

This function can be very useful if you want to initialize a variable in different ways depending on the execution conditions. Naive example:

 let x: u32; if condition { x = 1; } else if other_condition { x = 10; } else { x = 100; } 

But still, it will be an error if there is a chance that it is not initialized:

 let x: u32; if condition { x = 1; } else if other_condition { x = 10; } // no else println!("{:?}", x); // Error: use of possibly uninitialized variable: `x` 
+12
source

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.

+8
source

Source: https://habr.com/ru/post/1266967/


All Articles