Rust, Software Development

What Are References In Rust And How To Use Them?

Rust Lang

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 reference is not the same as the traditional pointers from C/C++.

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. By the ownership rule, there can only be one owner of that instance. 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.

When we build our codes, the Rust Compiler gives out the following error.

By default, variable bindings move values. If we want to copy values, we need to 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 used &my_profile, even for 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, variable assignment, as shown earlier. Another, using a variable as a parameter to a function. Lastly, using 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’s gone 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 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.

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *