Rust Essentials(Second Edition)
上QQ阅读APP看书,第一时间看更新

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.