首页 > 解决方案 > 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)
    }
}

但是还是有错误。

标签: rust

解决方案


FnBox从未稳定过。当你想要一个Box<dyn FnOnce()>但这种类型并没有用来实现FnOnce自身时,它更像是一种黑客攻击。

因为自 Rust 1.35 以来的Box<dyn FnOnce()>实现FnOnceFnBox已在 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);
    }
}

永久链接到操场


推荐阅读