Can anyone explain why below happens? I thought x.borrow().val
returns copy of i32
typed value, instead of referencing the memory pointed by x
?
use std::cell::RefCell;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct Foo {
pub val: i32,
}
pub fn demo() -> i32 {
let x = RefCell::new(Foo{ val: 10 });
x.borrow().val
}
Compiling playground v0.0.1 (/playground)
error[E0597]: `x` does not live long enough
--> src/lib.rs:11:5
|
11 | x.borrow().val
| ^---------
| |
| borrowed value does not live long enough
| a temporary with access to the borrow is created here ...
12 | }
| -
| |
| `x` dropped here while still borrowed
| ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `Ref<'_, Foo>`
|
= note: the temporary is part of an expression at the end of a block;
consider forcing this temporary to be dropped sooner, before the block's local variables are dropped
help: for example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block
|
11 | let x = x.borrow().val; x
| ^^^^^^^ ^^^
Besides, can anyone help me understand what does this mean from above error message?
the temporary is part of an expression at the end of a block;
consider forcing this temporary to be dropped sooner, before the block's local variables are dropped