Why must we borrow the type and not the name of the variable

Viewed 221

In the following code:

struct Book {
    pages: i32,
    rating: i32,
}

fn display_page_count(book: &Book) {
    println!("Pages = {:?}", book.pages);
}

fn display_rating(book: &Book) {
    println!("Rating = {:?}", book.rating);
}

fn main() {
    let book = Book {
    pages: 5,
    rating: 9,
    };
    display_page_count(&book);
    display_rating(&book);
}

Why do we write fn display_page_count(book: &Book) and not fn display_page_count(&book: Book)? For me, book is the data we’ll want to borrow later, Book is just a type (a struct here), so I don’t understand why we have to borrow the type and not the variable or parameter. Can someone tell me why I’m wrong?

2 Answers

In fn display_rating(book: &Book) declaration, the book is the name of the variable that has the type &Book.

Using the fn display_rating(book: Book) notation would mean that the ownership is passed down to the function and without returning it, it could not be used in the outer scope.

The book: &Book means that we are using the reference to the variable. And in this case book could have any name you want because it's just the name of the variable with type &Book.

Because this is to declare a variable's name and not to tag a type.

When declaring, all variables must be pure names, names cannot be references.

The situation of & and & mut tag before a variable, is just to tag the variable's type, not the name.

This is because you just gave an object a name. It is the object's type that changes, not the name.

Related