Borrow
We'll cover the following...
Let’s keep the momentum going from our lesson on ownership! We spent a lot of time playing around with ownership and moving, and we found it really annoying (or, at least, I did) that we had to keep moving values into functions and then back out. It would be nice to have a better solution for it. With that kind of introduction, you better believe that’s what we’re about to learn.
Here’s another look at some of that move-in-move-out code we had before:
In particular, this line really bothers me:
I don’t want to have to move the value in and back out. Instead, I’d like to be able to let print_fruit borrow the value I own in main, without moving it completely. Rust supports exactly that! Let’s work through changing the code, and then we’ll explain some details.
First, instead of passing print_fruit the fruit value itself, we need to pass it a borrowed reference. There’s a new unary operator to learn for this, &.
NOTE: Does that ...