Variables are memory addresses used to store information to be referenced and manipulated in programs. They also provide a way of defining data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program in accordance with its scope.
Let us take an example Rust program which prints out GeeksForGeeks with and without storing it in a variable.
In the above program, we have printed two output:
- In the first print statement, we have directly printed the output without storing the value in a variable.
- But in the second one, we have used the variable “x” to store the value ‘GeeksForGeeks” and then used the variable instead.
Declaring a variable
In Rust, we can create variables by assigning data to alphanumeric words( excluding keywords) using the let keyword or const keyword.
Syntax: let x = "Value"; or const x = "Value";
In the above program, we used the variable “x” to store the string “GeeksForGeeks”
- The let keyword (or const keyword) suggests the compiler to consider the letter “x” to be the label of string “GeeksForGeeks” in the memory.
- The mut keyword can be added after let keyword or const keyword to make the variable mutable.
- Rust compiler can detect the data type of the variable, but you can also explicitly define the data type of the variable.
Immutability or an immutable object is an object whose state or valve cannot be modified after it is created or assigned. Whereas mutability or a mutable object is an object whose state or valve can be modified after it is created or assigned. By default all rust variables are immutable.
Let us take an example program where we try to change variable value which gives us an error
As you can see from the picture the program couldn’t be compiled and gave us an error. As rust compiler detected it was asking to use “mut x” instead of plain x. The mut is a keyword used in rust to say that the object or variable is mutable. Let us add mut and try again.
In the above rust programs we have used let keyword before the variable, let and const are the same as they are in other programming languages. In Rust, you aren’t allowed to use the mut keyword with constants, Constants aren’t immutable by default.
Example: An example of a constant variable.
We can also declare multiple variables in a single line as shown below:
geeks for geeks is amazing
Shadowing is an instance where we can make a variable mutable temporarily. Rust supports shadowing of variables. Shadowing also allows changing the data type of variable. In Rust, you can declare a new variable that has the same name as a previously declared variable which shadows the previous variable meaning the second variable’s value is what appears when the variable is used.
The value of gfg is: 250