Rust:为什么将闭包绑定到变量会改变类型?
我有这个(最简化的)代码:
fn returns_closure() -> Box<dyn Fn(&u64)> {
let closure = |_| ();
Box::new(closure)
}
这不会编译并带有相当无用的错误消息:
error[E0308]: mismatched types
--> src/main.rs:3:5
|
3 | Box::new(closure)
| ^^^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected type `FnOnce<(&u64,)>`
found type `FnOnce<(&u64,)>`
error[E0308]: mismatched types
--> src/main.rs:3:5
|
3 | Box::new(closure)
| ^^^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected type `FnOnce<(&u64,)>`
found type `FnOnce<(&u64,)>`
但是,当我不先将闭包绑定到变量,而是直接在 Box 的构造函数中创建它时,它确实会编译:
为什么第一个编译失败,两者有什么区别?
编辑:埃蒙斯的回答似乎是正确的。我用 nightly 工具链 (1.52.0) 编译了完全相同的代码,得到了一个更好的错误:
error: implementation of `FnOnce` is not general enough
--> src/main.rs:3:5
|
3 | Box::new(closure)
| ^^^^^^^^^^^^^^^^^ implementation of `FnOnce` is not general enough
|
= note: closure with signature `fn(&'2 u64)` must implement `FnOnce<(&'1 u64,)>`, for any lifetime `'1`...
= note: ...but it actually implements `FnOnce<(&'2 u64,)>`, for some specific lifetime `'2`