Rust, Software Development

What Are References In Rust And How To Use Them?

Understanding what references are in Rust and how to use them is crucial. A reference is a pointer to a memory location. A location where the data we’re interested in reside. A Rust reference is similar to the traditional pointers from C/C++ but not the same.

What Are References?

Consider the Person struct below. We create an instance and assign it to the my_profile variable.

The variable my_profile holds and owns the instance of Person. There can only be one owner of that instance by the ownership rule. Then, we assign the instance to another variable named my_temp_profile.

Again, by the ownership rule, only one owner is allowed. At this point, the instance of the Person has a new owner!

Then, we reuse my_profile variable in our codes, as shown below.

The Rust Compiler gives out the following error when we build our codes.

By default, variable bindings move values. If we want to copy values, we must implement both the Copy and Clone traits. We’ll stick with the default behavior for this post.

So, how do we fix the compilation error? We use references. Our revised codes are as follows.

We assigned &my_profile, even to my_temp_profile and my_original_profile. Now, those two variables are just borrowing the instance of the Person. The variable my_profile is still the sole owner of that instance.

How To Use References In Rust?

What are the occasions that lead to an E0382 Rust error? One is the variable assignment, as shown earlier. Another is using a variable as a parameter to a function. Lastly, use it in a closure (non-local to the closure block).

Consider the modified codes below. We are now passing my_profile to a function. When we compile them, we get the same E0382 error.

Who owns the Person instance now? Nobody. It goes away as soon as the process_profile function completes. To fix the error, we use references.

Our updated codes should look something like the following.

So far, we have looked at immutable references. With immutable references, we can borrow values (struct instances in this case), but we cannot modify them. References can also be mutable.

This post is part of the Rust Programming Language For Beginners Tutorial.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like