Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 211
guillaume8375 Avatar asked Nov 07 '22 00:11

guillaume8375


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

like image 113
Nikita Zavyalov Avatar answered Dec 19 '22 21:12

Nikita Zavyalov