I am learning Rust's lifetime/ownership concepts, and would like to explain the following behavior in Rust (rustc 1.37.0).
For a program like this:
#[derive(Debug)]
struct Book {
price: i32,
}
fn main() {
let book1 = Book {price: 12};
let cheaper_book = choose_cheaper(&book1);
println!("{:?}", cheaper_book);
}
fn choose_cheaper(b1: &Book) -> &Book {
if b1.price < 15 {
b1
} else {
let cheapest_book = Book {price: 0};
&cheapest_book
}
}
Rust reports:
17 | &cheapest_book
| ^^^^^^^^^^^^^^ returns a reference to data owned by the current function
And I can understand this error and it is because variable cheapest_book
is the owner of the Book with price 0, and it will be dropped at the end of this function, so the returned reference will become invalid after that. But it is hard for me to explain why the following is allowed if I change the choose_cheaper
function to be:
fn choose_cheaper(b1: &Book) -> &Book {
if b1.price < 15 {
b1
} else {
let cheapest_book = &Book {price: 0};
cheapest_book
}
}
Could some one shed me some light on it? Thanks.