从RefCell返回引用

时间:2018-07-14 17:11:56

标签: rust borrow-checker interior-mutability

为什么该程序无法编译

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()),
    };
}

它给出消息:

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

0 个答案:

没有答案