Rust declare variable
More actions
Declaring a variable
edit edit sourceThe syntax for declaring variables in Rust is:
let VARIABLE_NAME: TYPE;
The VARIABLE_NAME should be set to any alpha-numerical string, and can also include underscores. See naming variables for a guide on how to name variables, and Rust identifier naming conventions for advice on common conventions.
Example of declaring a variable
edit edit sourcelet name: String;
Declare and initialize together
edit edit sourceYou can also both create (declare) and initialize (set the value of) a variable in one line:
let VARIABLE_NAME: TYPE = VALUE;
There is more info on initializing variables in Rust on the Rust initialize variable page.
Example of declaring and initializing a variable
edit edit sourcelet town: &str = "Paris";
Type inference
edit edit sourceThe Rust compiler is clever enough to infer the type of a variable based on the value we assign it.
We still need to give it a value at some point, otherwise it's impossible for the compiler to know what type to give it.
Example of type inference
edit edit sourcelet age = 21;
In this example, the compiler will infer that the type of age is an i32, a signed 32-bit integer (number).