Returning reference from RefCell [duplicate]

旧巷老猫 提交于 2019-12-11 08:40:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!