![]() |
VOOZH | about |
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:
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:
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