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:

Press + to interact
struct Fruit {
apples: i32,
bananas: i32,
}
fn increase_fruit(mut fruit: Fruit) -> Fruit {
fruit.apples *= 2;
fruit.bananas *= 3;
fruit
}
fn print_fruit(fruit: Fruit) -> Fruit {
println!("You have {} apples and {} bananas", fruit.apples, fruit.bananas);
fruit
}
fn main() {
let fruit = Fruit {
apples: 10,
bananas: 5,
};
let fruit = print_fruit(fruit);
let fruit = increase_fruit(fruit);
print_fruit(fruit);
}

In particular, this line really bothers me:

Press + to interact
let fruit = print_fruit(fruit);

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 look ...