rust - FnBox 示例抛出错误:盒装中没有 FnBox?
问题描述
我试图从官方文档FnBox
中运行该示例,但它抛出了一个错误:
error[E0432]: unresolved import `std::boxed::FnBox`
--> src/main.rs:4:5
|
4 | use std::boxed::FnBox;
| ^^^^^^^^^^^^^^^^^ no `FnBox` in `boxed`
使用 rust playground很容易得到这个错误,我在本地也遇到了同样的错误。
实际上我在本地发现了一些来自 std 的声明:
#[rustc_paren_sugar]
#[unstable(feature = "fnbox",
reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
pub trait FnBox<A>: FnOnce<A> {
/// Performs the call operation.
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
#[unstable(feature = "fnbox",
reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
impl<A, F> FnBox<A> for F
where F: FnOnce<A>
{
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
但是还是有错误。
解决方案
FnBox
从未稳定过。当你想要一个Box<dyn FnOnce()>
但这种类型并没有用来实现FnOnce
自身时,它更像是一种黑客攻击。
因为自 Rust 1.35 以来的Box<dyn FnOnce()>
实现FnOnce
,FnBox
已在 Rust 1.37 中删除。
的所有用法Box<FnBox<_>>
都可以替换为Box<FnOnce<_>>
,例如旧文档示例:
use std::collections::HashMap;
fn make_map() -> HashMap<i32, Box<dyn FnOnce() -> i32>> {
let mut map: HashMap<i32, Box<dyn FnOnce() -> i32>> = HashMap::new();
map.insert(1, Box::new(|| 22));
map.insert(2, Box::new(|| 44));
map
}
fn main() {
let mut map = make_map();
for i in &[1, 2] {
let f = map.remove(&i).unwrap();
assert_eq!(f(), i * 22);
}
}
(永久链接到操场)
推荐阅读
- python - 如何通过指定上限和下限来查找字典中的键
- kubernetes - Kubernetes 创建部署意外的 SchemaError
- ios - 如何在 App Swift 4 中停止屏幕录制
- c# - 如何在不删除已保存数据的情况下更新序列化的 bin 文件?
- django - ModuleNotFoundError:没有名为“django.urls”的模块在 Django 1.9 中不起作用
- apache - 无查询重定向
- python - 在 tkinter 中按下按钮时如何获取鼠标位置?
- reactjs - 单击模态按钮时如何防止呈现
- python - ModuleNotFoundError:没有名为“__main__.web_app”的模块;从子文件夹导入包时,'__main__' 不是包
- css - CSS红色方块在顶部