我正在像这样将闭包存储在结构体中:
#[derive(Clone)]
struct S<'a> {
func: &'a FnOnce() -> u32
}
fn main() {
let s = S { func: &|| 0 };
let val = (s.func)();
println!("{}", val);
}
当我编译时,
s.func
不能被移动以执行自身。我理解为什么它不能被移动(即它只是一个引用,其大小在编译时未知),但不知道为什么它被移动了 - 是因为通过特性实现了闭包吗?以下是错误消息:
error[E0161]: cannot move a value of type std::ops::FnOnce() -> u32:
the size of std::ops::FnOnce() -> u32 cannot be statically determined
--> main.rs:8:15
|
8 | let val = (s.func)();
| ^^^^^^^^
error[E0507]: cannot move out of borrowed content
--> main.rs:8:15
|
8 | let val = (s.func)();
| ^^^^^^^^ cannot move out of borrowed content
error: aborting due to 2 previous errors
这是唯一的解决方法吗?将闭包存储在堆上(通过Box<FnOnce() -> u32>
)?为什么调用闭包会移动它?推测调用闭包并不会改变函数本身。
Fn
而不是FnOnce
,因为我想创建一个结构体的const实例,但整个回复对于理解整个问题都非常有帮助。 - cderwin