Open In App

Rust – Aliasing

Last Updated : 15 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Rust is statically typed and there is a concept of Alias which states that data can be borrowed immutably but during borrowing, the original data cannot be borrowed mutably. Aliasing is useful for the optimization of data.

In Aliasing, only one data can be mutably borrowed at a time. On the condition that mutable reference has been used previously, only then the original data can be borrowed.

Let us see this example to understand Aliasing in Rust. We have three variables x,y, and z in Struct GFG, and variable1 and variable2 refer to GFG.

Now, data can be accessed via references (geeks_variable) and the original owner (GFG).

Example 1:

Rust




// Rust code for Aliasing
#![allow(dead_code)]
struct GFG { 
// Default value of integer in integer is i32
a: i32, 
b: i32, 
c: i32 
    }
  
fn main() {
  
    let geeks_variable = GFG { a: 1, b: 2, c: 3 };
  
    let variable1 = &geeks_variable;
    let variable2 = &geeks_variable;
println!("GFG has variables: ({}, {}, {})",
                variable1.a, variable2.b, geeks_variable.c);
                }


Output:

 

Here, we cannot borrow geeks_variable as mutable because it is currently borrowed as immutable.  As immutable references are no longer used now, therefore we reborrow a mutable reference (mutable_reborrow_variable) and then we change the data using mutable references.

Example 2:

Rust




// Rust code 
struct GFG { 
// Default value of integer in integer is i32
a: i32, 
b: i32, 
c: i32 
    }
  
fn main() {
    let mut geeks_variable = GFG { a: 1, b: 2, c: 3 };
  
    let variable1 = &geeks_variable;
    let variable2 = &geeks_variable;
  
  
    println!("GFG has variables: ({}, {}, {})",
    variable1.a, variable2.b, geeks_variable.c);
  
    let mutable_reborrow_variable = &mut geeks_variable;
  
    mutable_reborrow_variable.a = 10;
    mutable_reborrow_variable.b = 20;
    mutable_reborrow_variable.c = 30;
  
    println!("GFG now has immutable variables: ({}, {}, {})",
      mutable_reborrow_variable.a, mutable_reborrow_
      variable.b, mutable_reborrow_variable.c);
  
   
    let new_reborrow = &geeks_variable;
    println!("GFG now has reborrowed variables: ({}, {}, {})",
     new_reborrow.a, new_reborrow.b, new_reborrow.c);
}


Output:

 

 

Here, we see that we had passed mutable references to println! using the mutable_reborrow_variable. Again, we see the mutable reference is not used for the rest of the code and hence we reborrow it using the variable new_reborrow



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads