Rust – References & Borrowing
As Rust Ownership rules say one owner at a time but there might some cases where we need to perform an action on data without affecting its original value. This is done via borrowing. Borrowing is like in general when we borrow something, and we are done with it, we give it back, but this doesn’t make us the owner of the data. Reference is an address that is passed to a function as an argument, and they always start with ampersand(&).
Rules of References
- At any given time, you can have either one mutable reference or any number of immutable references.
- References must always be valid.
Let taken an example
The variable gfg contains a string and is passed on to a function calculate_length as a reference which means gfg_len borrows the value of variable gfg to calculate its length, and it returns the borrowed at the end of the function. The function then returns the length of the passed reference string.
Visual Representation of References:
Now let us try to change the value of the borrowed program and see what we get
References and Mutability
Like variables in Rust, all references are mutable by default. Let us try to change the value we are referencing.
This gives an error because values borrowed can’t be modified because we aren’t the owner of the value.
Rust supports mutable references which means we can change the value it references if it’s a mutable variable. There are some restrictions on how we use mutable references.
- You can have only one mutable reference to a particular value in a particular scope to prevent data races
- If the immutable reference exists in our program then We can’t have a mutable reference into the same value.
- You can have multiple immutable references in a particular scope because we can’t change the value it references to
Let us change the program above to be valid