wiki/dev/lang/rust/Variable.md

938 B

Variables.

Definition.

Immutable.

Use the let keyword to start declaration. Types are specified after the variable name.

let x: i32 = 10;

Type definition is optional, so you can drop it. I suggest specifying the type for global/class/etc variables, but dropping it in local scope like functions.

let x = "This is &str"; // Type is detected automatically: &str.

Mutable.

Add mut keyword after let.

let mut x: i32 = 10;
x = 12;

Constants.

To declare constant, use the const keyword instead of let. Constant values always require type definition.

const NUMBER: i32 = 10;

Shadowing.

You can redefine a variable with the same name but with a different type. This is useful if you cast something, but want to keep the same variable name. To do this, just declare the variable again.

let x: &str = "&str"; // &str.
let x: i32  = 10;     // i32.