Returning reference from RefCell [duplicate]

2019-07-31 02:44发布

问题:

This question already has an answer here:

  • How do I borrow a RefCell<HashMap>, find a key, and return a reference to the result? [duplicate] 1 answer
  • How do I return a reference to something inside a RefCell without breaking encapsulation? 3 answers

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 | |     }
   | |_____^