Rust Variables

In this tutorial you will learn about the Rust Variables and its application with practical example.

What is Variables?

Variables is an identifier used to refer memory location in computer memory that holds a value for that variable, this value can be changed during the execution of the program. When you create a variable in Rust, this means you are allocating some space in the memory for that variable. The size of memory block allocated and type of the value it holds is completely dependent upon the type of variable.

Declaring Variables In Rust

In Rust, we can declare variable bindings first, and initialize them later. In Rust, variables are declared using the let keyword followed by variable name that you want to declare, optionally a colon (:) and then the data type you want to hold in that variable.

Syntax:-

or

Initializing Variables In Rust

In Rust, a variable bindings must be initialized with a value before they are used. The assignment operator (=) is used to assign values to a variable, the operand in the left side of the assignment operator (=) indicates the name of the variable and the operand in the right side of the assignment operator (=) indicates the value to be stored in that variable.

Syntax:-

or

or

or

Example:-

Output:-

rust_variable_initialization

Type Annotations

Rust is a type inferred language, which allows us to drop the type annotation from the declaration. In Rust, compiler automatically infer(know) the type of data we want to store based on the initial value we assign. In Rust, this feature is termed as ‘type inference’.

Recommended:-  Rust Data Types

Example:-

Here, type annotation is not used in the declaration but the Rust compiler simply infer the type automatically for us.

Rust Mutability

In Rust, by default variables are immutable. Once a variable is assigned an initial value, you will not allowed to change that value.

Example:-

This will result in error –

However, if you still have the option to make your variables mutable by adding the mut keyword in front of variable name.

Example:-

Printing Variables or String Interpolation

In Rust, println!() function is used to print the current value of a variable. String interpolation can be done by including two curly braces ({}) in your string to print, Rust compiler will interpret this as a request to interpolate with some value. Next, the comma is used to separate arguments we are interpolating with.

Example:-

Output:-

rust_print_variable_value_string_interpolation

In this tutorial we have learn about the Rust Variables and its application with practical example. I hope you will like this tutorial.