1

为什么这个程序无法编译

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

0 回答 0