尽管受到限制,但价值还不够长

Value doesn't live long enough, despite being constrained to

以下 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 稳定版得到的错误是:

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 一样长,因为它受到限制。我错过了什么,我该如何解决这个错误?

ffrom 方法的局部变量,因此所有引用都是对它的引用。 你想要的是:

pub struct UserAction<'u> {
    _act: &'u mut (FnMut() + 'u)
}

impl<'u, F: FnMut() + 'u> From<&'u mut F> for UserAction<'u> {
//                             ^^^^^^^
    fn from(f: &'u mut F) -> Self {
//             ^^^^^^^
        UserAction { _act: f as &'u mut (FnMut() + 'u) }
    }
}

作为 ,您将闭包的所有权传递给函数,然后尝试引用它。很高兴编译器发现了错误并阻止您使用对某些会导致内存损坏的范围外变量的引用。

限制 F: FnMut() + 'u 指出 F 必须是实现 FnMut 特征的类型,并且 包含比生命周期 =15=]。它并没有说 F 本身必须超过那个生命周期。事实上,我们可以看到 f 在方法退出后没有所有者,因此它的生命周期结束 - 因此错误。

最直接的等效方法是使用 盒装特征对象 而不是 特征对象引用 :

pub struct UserAction<'u> {
    _act: Box<FnMut() + 'u>,
}

impl<'u, F: FnMut() + 'u> From<F> for UserAction<'u> {
    fn from(f: F) -> Self {
        UserAction { _act: Box::new(f) }
    }
}

另一种替代方法是渗透通用类型:

pub struct UserAction<F> {
    _act: F,
}

impl<F: FnMut()> From<F> for UserAction<F> {
    fn from(f: F) -> Self {
        UserAction { _act: f }
    }
}