官术网_书友最值得收藏!

Mutable and immutable variables

Suppose we get a boost from swallowing a health pack and our energy rises to a value of 25. However, if we assign the value to the variable energy as follows:

energy = 25;

We get an error, as follows:

error: re-assignment of immutable variable `energy`.

What is wrong here?

Well, Rust applies programmer's wisdom here: a lot of bugs come from inadvertent or wrong changes of variables, so don't let code change a value unless you have deliberately allowed it!

Variables are, by default,immutable, in Rust, which is very similar to what functional languages do (in pure functional languages, mutability is not even allowed).

If you want a mutable variable, because its value can change during code execution, you have to indicate that explicitly with the mut variable, for example:

  let mut fuel = 34; 
  fuel = 60; 

Simply declaring a variable as let n; is also not enough. We get the following error:

error: type annotations needed, consider giving `energy2` a type, cannot infer type for `_`

Indeed, the compiler needs a value to infer its type.

We can give the compiler this information by assigning a value to the variable n, like n = -2; but as the message says, we could also indicate its type as follows:

  let n: i32; 

Or:

let n: i32 = -2; // n is a binding of type i32 and value -2 

The type (here i32) follows the variable name after a colon : (as we already showed for global constants), optionally followed by an initialization. In general the type is indicated like this-n: T where n is a variable and T a type, and it reads, variable n is of type T. So, this is the inverse of what is done in C or C++, Java or C#, where one would write Tn.

For the primitive types, this can also be done simply with a suffix, as follows:

let x = 42u8; 
let magic_number = 3.14f64; 

Trying to use an uninitialized variable results in the following error:

error: use of possibly uninitialized variable

Local variables have to be initialized before use in order to prevent undefined behavior. When the compiler does not recognize a name (for example, a function name) in your code, you will get the following error:

error: not found in this scope error

It is probably just a typo, but it is caught early on at compilation, and not at runtime!

主站蜘蛛池模板: 金阳县| 钟山县| 大洼县| 晋城| 贵州省| 通道| 开原市| 南康市| 宣恩县| 宁乡县| 高陵县| 双江| 上栗县| 巴东县| 水富县| 万盛区| 黄龙县| 泗水县| 固始县| 山丹县| 眉山市| 县级市| 大悟县| 兴山县| 米泉市| 黔南| 石棉县| 家居| 兴化市| 湾仔区| 滁州市| 柘荣县| 肇东市| 绍兴县| 波密县| 饶平县| 汉中市| 辛集市| 兰溪市| 永泰县| 缙云县|