问题
Why does this program not compile
use std::cell::RefCell;
struct S {
field: RefCell<String>,
}
impl S {
fn take_ref(&self) -> &str {
&self.field.borrow()
}
}
fn main() {
let s = S {
field: RefCell::new("abc".to_string()),
};
}
it gives the message:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:9:10
|
9 | &self.field.borrow()
| ^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough
10 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 8:5...
--> src/main.rs:8:5
|
8 | / fn take_ref(&self) -> &str {
9 | | &self.field.borrow()
10 | | }
| |_____^
来源:https://stackoverflow.com/questions/51341643/returning-reference-from-refcell