- Rust Essentials(Second Edition)
- Ivo Balbaert
- 403字
- 2021-07-02 15:30:38
Binding variables to values
Storing all values in constants is not an option. It is not good because constants live as long as the program and moreover can't change, and often we want to change values. In Rust, we can bind a value to a variable by using a let binding.
// see Chapter 2/code/bindings.rs fn main() { let energy = 5; // value 5 is bound to variable energy }
Unlike in many other languages, such as Python or Go, the semicolon,;, is needed here to end the statement. Otherwise, the compiler throws an error, as follows:
error: expected one of `.`, `;`, or an operator, found `}`
We also want to create bindings only when they are used in the rest of the program, but don't worry, the Rust compiler warns us about that. The warning looks like the following:
values.rs:2:6: 2:7 warning: unused variable: `energy`, #[warn(unused_variables)] on by default
For prototyping purposes, you can suppress that warning by prefixing the variable name with an _, like in let _ energy = 5; in general _ is used for variables we don't need.
Notice that in the declaration above we did not need to indicate the type. Rust infers the type of the energy variable to be an integer; the let binding triggers that. If the type is not obvious, the compiler searches in the code context where the variable gets a value or how it is used.
But giving type hints like let energy = 5u16; is also OK; that way, you help the compiler a bit by indicating the type of energy, in this case a two-byte unsigned integer.
We can use the variable energy by using it in an expression, for example assigning it to another variable, or printing it:
let copy_energy = energy; println!("Your energy is {}", energy););
Here are some other declarations:
let level_title = "Level 1"; let dead = false; let magic_number = 3.14f32; let empty = (); // the value of the unit type ()
The value of the magic_number variable could also be written as 3.14_f32; the _ separates the digits from the type to improve readability.
Declarations can replace previous declarations of the same variable. Consider a statement like the following:
let energy = "Abundant";
It would now bind the variable energy to the value Abundant of type string. The old declaration can no longer be used and its memory is freed.
- SQL Server 從入門到項目實踐(超值版)
- Interactive Data Visualization with Python
- Vue.js入門與商城開發實戰
- 體驗設計原理:行為、情感和細節
- INSTANT MinGW Starter
- oreilly精品圖書:軟件開發者路線圖叢書(共8冊)
- Learning Network Forensics
- C語言實驗指導及習題解析
- 自然語言處理Python進階
- Go并發編程實戰
- 精通Python自動化編程
- 區塊鏈技術進階與實戰(第2版)
- Python大學實用教程
- Hands-On Dependency Injection in Go
- ASP.NET Core and Angular 2