rustborrow-checkerownershipampersand

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


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?


Solution

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