Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Rust declare variable

From Programming Wiki

Declaring a variable

edit edit source

The 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 source
let name: String;

Declare and initialize together

edit edit source

You 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 source
let town: &str = "Paris";

Type inference

edit edit source

The 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 source
let age = 21;

In this example, the compiler will infer that the type of age is an i32, a signed 32-bit integer (number).