【发布时间】:2021-12-26 19:54:46
【问题描述】:
如果我按照 rustc 告诉我的操作,以下错误就会消失,并将绑定更改为
where F: Fn() -> () + 'static
pub struct Struct(Box<dyn Fn() -> ()>);
pub fn example<F>(f: F)
where
F: Fn() -> ()
{
Struct(Box::new(|| ())); // ok
Struct(Box::new(f)); // error: The parameter type `F` may not live long eneough
// help: consider adding an explicit lifetime bound: `F: 'static`
}
但是,我只是不明白这里的“静态”是什么意思。这似乎并不意味着 闭包本身永远存在。
至少,关闭似乎不会永远存在。如果我让闭包拥有一些数据,那么这些数据会在某个时候被丢弃,这让我怀疑闭包被丢弃:
pub struct Struct(Box<dyn Fn() -> ()>);
#[derive(Debug)]
struct DropMe;
impl Drop for DropMe {
fn drop(&mut self) {
println!("dropped");
}
}
/// prints:
/// "got DropMe"
/// "got DropMe"
/// "dropped"
/// "end of program"
pub fn main() {
let d = DropMe;
example(move || {
println!("got {:?}", d);
});
println!("end of program")
}
pub fn example<F>(f: F)
where
F: Fn() -> () + 'static
{
let s = Struct(Box::new(f));
s.0();
s.0();
}
'static 是闭包生命周期的上限而不是下限吗? 'static 作为上限是有意义的,然后 example 会说“给我一个我可以随心所欲地坚持的功能”,实际上它可能小于 'static 的生命周期。
如何判断+ 'lifetime 何时添加'lifetime 作为上限和下限?
subtyping+variance 上的 Rustonomicon 章节似乎没有涵盖这一点,而且我在 Rust 书籍或 Rust 参考中找不到我想要的信息。
【问题讨论】: