copied successfully!
When should I pass a reference
What is the problem with the following code?
fn print_book(book: Book) {
println!("Book: {}", book.title);
}
fn do_something_else(book: Book) {
println!("Again: {}", book.title);
}
fn main() {
let book = Book {
title: String::from("The Rust Programming Language")
};
print_book(book);
do_something_else(book);
}
The problem with this code is related to Rust's ownership rules. In the
main
function, book
is moved into the print_book
function and then it goes out of scope at the end of that function. This means that book
is no longer valid in the main
function, so it can't be passed to the do_something_else
function afterwards, which leads to a compile-time error.
To fix it, you can pass a reference to the book
instead of moving it, which would allow you to use it multiple times:
fn print_book(book: &Book) {
println!("Book: {}", book.title);
}
fn do_something_else(book: &Book) {
println!("Again: {}", book.title);
}
Or you could clone the book
so that each function gets its own copy:
fn print_book(book: Book) {
println!("Book: {}", book.title);
}
fn do_something_else(book: Book) {
println!("Again: {}", book.title);
}
fn main() {
let book = Book {
title: String::from("The Rust Programming Language")
};
print_book(book.clone());
do_something_else(book);
}
In both revised examples, book
can be used multiple times since ownership is not transferred to the print_book
or do_something_else
functions.