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

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.

主站蜘蛛池模板: 华池县| 江山市| 周宁县| 息烽县| 怀来县| 玛纳斯县| 勃利县| 乌鲁木齐县| 武鸣县| 平陆县| 视频| 布尔津县| 常熟市| 环江| 胶南市| 宣武区| 天长市| 贵州省| 永善县| 申扎县| 昭苏县| 苗栗市| 中超| 星子县| 淳化县| 望江县| 丹阳市| 颍上县| 黑山县| 葫芦岛市| 通许县| 桐城市| 长宁区| 古交市| 调兵山市| 临城县| 凤翔县| 靖远县| 新竹市| 扎囊县| 宜黄县|