考虑以下简单示例:
use std::cell::RefCell;
// Compiles fine
fn good(t: RefCell<String>) -> bool {
t.borrow().len() == 12
}
// error[E0597]: `t` does not live long enough
fn bad(t: RefCell<String>) -> bool {
let t = t;
t.borrow().len() == 12
}
该bad
函数无法编译并出现以下错误:
error[E0597]: `t` does not live long enough
--> src/lib.rs:9:5
|
8 | let t = t;
| - binding `t` declared here
9 | t.borrow().len() == 12
| ^---------
| |
| borrowed value does not live long enough
| a temporary with access to the borrow is created here ...
10 | }
| -
| |
| `t` dropped here while still borrowed
| ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `Ref<'_, String>`
|
= note: the temporary is part of an expression at the end of a block;
consider forcing this temporary to be dropped sooner, before the block's local variables are dropped
help: for example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block
|
9 | let x = t.borrow().len() == 12; x
| +++++++ +++
这对我来说看起来非常奇怪。仅将函数参数重新分配给局部变量会导致编译失败。你能解释一下为什么吗?