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

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.

主站蜘蛛池模板: 九龙坡区| 逊克县| 重庆市| 当涂县| 霞浦县| 铜鼓县| 丰城市| 清涧县| 天全县| 灌云县| 武安市| 大名县| 鹿邑县| 沁源县| 曲水县| 鲁山县| 若尔盖县| 大安市| 屯门区| 安乡县| 抚宁县| 双城市| 芒康县| 丰镇市| 阳城县| 义乌市| 卓尼县| 突泉县| 永顺县| 新竹市| 漠河县| 电白县| 台中县| 巴林右旗| 怀远县| 岳阳县| 西安市| 平塘县| 池州市| 崇礼县| 元氏县|