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

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.

主站蜘蛛池模板: 勐海县| 定西市| 伽师县| 司法| 白山市| 汉川市| 广丰县| 弥渡县| 吉安县| 邻水| 昌黎县| 正定县| 镇沅| 焉耆| 镇江市| 林口县| 华亭县| 镇原县| 安化县| 兴城市| 安图县| 雅江县| 和硕县| 天长市| 灵武市| 霞浦县| 龙里县| 英山县| 北辰区| 开平市| 子长县| 金乡县| 南投市| 新邵县| 遂宁市| 平凉市| 山丹县| 河北区| 邵武市| 梅州市| 揭阳市|