以下 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
一样长,因为它受到限制。我错过了什么,我该如何解决这个错误?
最佳答案
作为mcarton says ,您正在将闭包的所有权传递给函数,然后尝试引用它。很高兴编译器发现了错误并阻止您使用对某些会导致内存损坏的范围外变量的引用。
限制 F: FnMut() + 'u
声明 F
必须是实现 FnMut
特性和 的类型包含比生命周期 'u
还长的引用。它并没有说 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 }
}
}
关于compiler-errors - 尽管受到限制,但值(value)还不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339755/