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

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!

主站蜘蛛池模板: 三河市| 正安县| 平凉市| 武鸣县| 石阡县| 永善县| 大化| 侯马市| 星座| 临江市| 东宁县| 固阳县| 阜新市| 北安市| 塔城市| 伊吾县| 福州市| 历史| 会宁县| 固原市| 突泉县| 永顺县| 依兰县| 城口县| 河津市| 双峰县| 二连浩特市| 昌黎县| 淮滨县| 开平市| 阜康市| 凉城县| 枞阳县| 洪雅县| 左贡县| 安国市| 措勤县| 仲巴县| 博乐市| 灵川县| 郧西县|