【发布时间】:2016-07-12 22:17:36
【问题描述】:
以下 Rust 代码编译失败:
pub struct UserAction<'u> {
_act: &'u mut (FnMut() + 'u)
}
impl<'u, F: FnMut() + 'u> From<F> for UserAction<'u> {
fn from(f: F) -> Self {
UserAction { _act: (&mut f) as &'u mut (FnMut() + 'u) }
}
}
我从rustc 1.10 stable 得到的错误是:
lives.rs:7:38: 7:39 error: `f` does not live long enough
lives.rs:7 UserAction { _act: (&mut f) as &'u mut (FnMut() + 'u) }
^
lives.rs:6:31: 8:10 note: reference must be valid for the lifetime 'u as defined on the block at 6:30...
lives.rs:6 fn from(f: F) -> Self {
^
lives.rs:6:31: 8:10 note: ...but borrowed value is only valid for the scope of function body at 6:30
lives.rs:6 fn from(f: F) -> Self {
^
error: aborting due to previous error
我不知道为什么这是一个错误; F 类型的寿命至少与 'u 的寿命一样长,因为它受到限制。我错过了什么,我该如何解决这个错误?
【问题讨论】:
标签: compiler-errors closures rust lifetime