Open In App

Rust – Concept of Scope, Block, and Shadowing

Last Updated : 22 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Rust is a multi-paradigm programming language like C++ syntax that was designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. 

In this article, we will discuss the concepts behind the scope, block, and shadowing in Rust programming.

Scope and Block of a Variable:

The scope of a variable in Rust refers to the part of the code where one can access the variable.
In Rust, curly braces { } define the block scope where the variable access becomes restricted to local. Any variable outside the braces would be having global access i.e. access from anywhere inside the function.

 A collection of statements enclosed by braces { } are called blocks. To understand the concept of blocks, we need to understand variables.

Types of Variables:

  • Local Variables: Local variables are variables that are defined inside a function scope. Their scope remains inside the curly braces i.e. its scope and not accessible outside.
  • Global Variables:  Global variables are variables that are declared outside the blocks and hence can be accessed inside any further blocks. They are accessible anywhere.

Example 1:

Rust




fn main() {
  let global_variable = "GeeksforGeeks" ; //
  { // start of code block
        let local_variable = "GFG"; //
        println!("Inner variable: {}", local_variable);
        println!("Outer variable: {}", global_variable);
  } // end of code block
}


Output:

 

Shadowing:

In Rust, we come across a  concept known as shadowing. Shadowing in a variable refers to a technique where a variable defined in a particular scope has the same name as a variable declared on another scope i.e. outer scope. This is referred to as masking. Therefore, the outer variable becomes shadowed by the inner variable, and the inner variable masks the outer variable.

Example 2:

Rust




fn main() {
  let outer_variable = "GeeksforGeeks_1";
  { // start of code block
        let inner_variable = "GFG";
        println!("The inner block variable is: {}", inner_variable);
        let outer_variable = "GeeksforGeeks_2";
        println!("The outer block variable : {}", outer_variable);
  } // end of code block
    println!("The outer variable is: {}", outer_variable);
  }


Output:

 

Here, outer_variable = “GeeksforGeeks_1″ is the variable that is outside the block, and outer_variable =” GeeksforGeeks_2″ is the variable that is inside the block.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads