Following on in my dive into the concept of ownership in Rust, will assess the idea of references and borrowing. I will follow the documentation at rust-lang.org. The tutorial breaks down the concept in three chunks:
-
Ownership (Covered in the previous post)
-
References and Borrowing
-
Lifetimes
In this post will summarize my general understanding of borrowing.
tl;dr: The concept of borrowing, prevents iterator invalidation, and use after free, helping to create a safer environment. If you want to mutate a passed variable, need to utilize a mutable reference.
Point #1:
Essentially, under references and borrowing, a resource is lent by the owner and “borrowed” by the function.
For example, consider the below as example given:
Point #2
References are immutable. Thus a variable passed by reference, lets say v1 in the above case, can not be amended within foo. Will give an error.
Point #3
If we want to mutate a borrowed variable, need to use a “mutable reference”. The example given is as follows:
The rules defined in the documentation:
First, any borow must last for a scope no greater than that of the owner. Second, you may have one or the other of these two kinds of borrows, but not both at the same time. 1) one or more references (&T) to a resource, 2) exactly one mutable reference (&mut T).