【发布时间】:2021-02-03 15:38:55
【问题描述】:
为什么下面的程序不能编译:
pub struct Textbox<'a,VM> {
get_element: Box<dyn Fn(VM)+'a>,
}
// Works
pub fn new<'a,VM,G:Fn(VM)+'a>(
get_element: G,
) -> Textbox<'a,VM> {
Textbox {
get_element: Box::new(get_element),
}
}
// Does not work. Compiler complains that we need
// a lifetime bound on VM.
// To the naive programmer writing this, it is unclear why,
// since the above function is accepted.
pub fn new_broken<'a,VM>(
get_element: fn(VM),
) -> Textbox<'a,VM> {
Textbox {
get_element: Box::new(get_element),
}
}
为什么 'new' 函数可以编译,但 'new_broken' 没有?是什么原因导致需要在“new_broken”中指定 VM 上的生命周期而不是在“new”中?
【问题讨论】: