The Wayback Machine - https://web.archive.org/web/20240601221219/https://www.geeksforgeeks.org/variables-in-rust/
Open In App

Variables in Rust

Last Updated : 03 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Rust




fn main() {
    println!("Welcome to GeeksForGeeks");
    let x = "GeeksForGeeks";
    println!("Welcome to {}", x);
}
  
// output without using variable
Welcome to GeeksForGeeks
  
// output using variable
Welcome to GeeksForGeeks


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";

Example:

Rust




fn main(){
  let x = "Geeksforgeeks";
  println!("{}",x);
}


Output:

Geeksforgeeks

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.

Mutability

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

Rust




fn main() {
    let x = 0;
    println!("The value of x is: {}", x);
    x = 1;
    println!("The value of x is: {}", x);
}


Output:

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.

compiled without errors

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.

Rust




fn main() {
  const N: i32 = 1;
  println!("num: {}", N);
}


Output:

num: 1

We can also declare multiple variables in a single line as shown below:

Example:

Rust




fn main() {
  let ( first, middle, last ) = ("geeks", "for","geeks");
  println!("{} {} {} is amazing", first, middle, last );
}


Output:

geeks for geeks is amazing

Shadowing

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.

Rust




fn main() {
  
    // original value of gfg 
    // variable is 100
    let gfg = 100;
      
    // gfg variable has value
    // 100-50 = 50 here
    // gfg variable got shadowed
    let gfg = gfg -50;
      
    // Again gfg variable has value
    // 50*5 = 250
    // gfg variable got shadowed again
    let gfg = gfg * 5;
  
    println!("The value of gfg is: {}", gfg);
}


Output:

The value of gfg is: 250


Similar Reads

Rust vs C++ - Will Rust Replace C++ in Future
We have seen many programming languages trending according to their functionality and popularity but languages are not meant to be used according to their popularity. We should consider the overall efficiency and productivity when it comes to using a programming language. Speaking of efficiency and popularity one of the most used programming langua
6 min read
Rust - Concept of Capturing Variables with Closers
In Rust, we can capture variables via Closures. Closures are anonymous functions that help us in saving variables or pass arguments to other functions. Closures can be created from one place and then can be called anywhere and they can capture values from their defined scope. While capturing variables, Rust uses the following methods to do this: by
2 min read
Rust - Bounds
In Rust, we have a concept of Bounds. Bounds are used in situations when we are working with generics and are trying to figure out the nature and type of parameters that are required for stipulating the functionality that the type in Rust implements. Syntax: fn gfg <T: GeeksforGeeks>(x: T) { println!(" {}", x); //more methods defined} In the
2 min read
Rust lifetime Constructor
In Rust, we have a concept of a lifetime constructor that falls under the ownership category. Rust enforces a certain set of rules through its concept of ownership and lifetimes. In this article, we would be learning more about Lifetimes in Rust. In Rust, there are various regions that are present in the code which are generally complex and referre
3 min read
Rust - Casting
Type Conversion or casting in Rust is a way to convert one type to another. As its name suggests, type conversion is the process of converting variables from one data type to another. So that, the compiler treats the variable as a new datatype. Rust doesn't allow us to implicitly convert the datatype between primitive types. The primitive types are
3 min read
Rust - Struct Visibility
In Rust, there is a concept of Struct Visibility. Generally, the items present in the module have visibility that is private by nature but we can override the private items by usage of the public ('pub') modifier. Public items of the module are accessed outside the module scope and the visibility in these scenarios is not very high. To avoid this s
3 min read
Rust - If let Operator
The basic difference between conventional if-else and if let is that if let uses one pattern that needs to be matched to an expression also known as scrutinee, if the pattern matches the expression then the corresponding code is executed, or in most cases that value is assigned according to it. Syntax : let gfg=value; let gfg_answer=if let value_1
2 min read
Rust - Reference Counted Smart Pointer
In Rust, there is a concept of a Smart pointer where we use multiple ownership explicitly using the Rc<T> type. This Rc <type> is referred to as Reference counting. This concept was introduced in Rust to handle scenarios where a single value of the variable has multiple owners. Rc<T> keeps how many references are made to a value a
2 min read
Rust - A Case of Safe Concurrency
Before looking at Rust itself, let's go back to 1992. Guido van Rossum, in an attempt to tackle race condition in CPython interpreter, added a lock famously known as the Global Interpreter Lock or GIL for short. Two and a half decades later, this was one of the main shortcomings for the Python interpreter we all love and use. So what is the Global
5 min read
Rust - Crate_type Attribute
In Rust, we have a concept of crates. Crates are basically libraries or packages as defined in other programming languages. Cargo, the rust package management tool helps ship the crates of our program to other programs' cargo. Crates produce an executable library where every crate has a root module that has the code for the crate. The crate_type at
2 min read
Article Tags :