如何构造带盒装 Fn 值的 HashMap

How to construct a HashMap with boxed Fn values

我对使用 Rust 还比较陌生,我在 Advent of Code 中使用它来帮助我学习。对于第四个问题,我想使用 HashMap 创建一个查找 table 以从字符串键映射到函数值。我知道 Rust 没有用于创建 HashMap 文字的语法糖,所以我从一个切片创建我的 HashMap。当我使用 fn 函数指针时,一切正常:

type ValidatorFn = fn(&str) -> bool;
...

    let validation_rules: HashMap<&str, ValidatorFn> = [
        ("byr", validate_birth_year as ValidatorFn), // "as" cast is necessary here...
        ("iyr", validate_issue_year),
        ("eyr", validate_expiration_year),
        ("hgt", validate_height),
        ("hcl", validate_hair_colour),
        ("ecl", validate_eye_colour),
        ("pid", validate_passport_id),
    ]
    .iter()
    .cloned()
    .collect();

但是,这限制了我只能存储使用 fn 关键字定义的函数,而不能存储闭包。作为练习,我想重写我的代码以使用盒装 Fn 特征对象而不是 fn 指针以允许使用闭包或函数。然而,我天真的尝试并没有奏效:

type ValidatorFn = Box<dyn Fn(&str) -> bool>;
...

    let validation_rules: HashMap<&str, ValidatorFn> = [
        ("byr", Box::new(validate_birth_year) as ValidatorFn),
        ("iyr", Box::new(validate_issue_year)),
        ("eyr", Box::new(validate_expiration_year)),
        ("hgt", Box::new(validate_height)),
        ("hcl", Box::new(validate_hair_colour)),
        ("ecl", Box::new(validate_eye_colour)),
        ("pid", Box::new(validate_passport_id)),
    ]
    .iter()
    .cloned()
    .collect();

给出多个编译器错误:

error[E0277]: the trait bound `dyn for<'r> Fn(&'r str) -> bool: Clone` is not satisfied
  --> src/main.rs:21:6
   |
21 |     .cloned()
   |      ^^^^^^ the trait `Clone` is not implemented for `dyn for<'r> Fn(&'r str) -> bool`
   |
   = note: required because of the requirements on the impl of `Clone` for `Box<dyn for<'r> Fn(&'r str) -> bool>`
   = note: required because it appears within the type `(&str, Box<dyn for<'r> Fn(&'r str) -> bool>)`
error[E0599]: no method named `collect` found for struct `Cloned<std::slice::Iter<'_, (&str, Box<dyn for<'r> Fn(&'r str) -> bool>)>>` in the current
 scope
   --> src/main.rs:22:6
    |
22  |     .collect();
    |      ^^^^^^^ method not found in `Cloned<std::slice::Iter<'_, (&str, Box<dyn for<'r> Fn(&'r str) -> bool>)>>`
    |
   ::: /Users/ryan/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/adapters/mod.rs:388:1
    |
388 | pub struct Cloned<I> {
    | -------------------- doesn't satisfy `_: Iterator`
    |
    = note: the method `collect` exists but the following trait bounds were not satisfied:
            `Cloned<std::slice::Iter<'_, (&str, Box<dyn for<'r> Fn(&'r str) -> bool>)>>: Iterator`
            which is required by `&mut Cloned<std::slice::Iter<'_, (&str, Box<dyn for<'r> Fn(&'r str) -> bool>)>>: Iterator`

有人可以帮助破译此错误消息并让我知道我正在尝试做的事情是否可行吗?它似乎在告诉我,不能克隆 Box 或其内容。我认为 Box 基本上只是指向堆上某处的指针,所以我不明白为什么不能克隆它?

构建哈希映射的正确方法是首先避免克隆:

let validation_rules: HashMap<&str, ValidatorFn> = vec![
    ("byr", Box::new(validate_birth_year) as ValidatorFn),
    ...
]
    .into_iter()
    .collect();

克隆在您的原始代码中是必需的,因为您正在迭代 references 到数组中的项目,并且 clone() 用作转换引用的便捷方式通过在引用后面生成对象的新副本,将其转换为实际对象。由于对象是 fn,它们本身是对函数的引用,因此没有发生昂贵的克隆,只是将一个指针从数组复制到 hashmap。

如果您使用 into_iter(),您会使用原始集合并迭代从中提取的实际值,因此您不需要克隆它们。不幸的是 into_iter() 是数组的 not yet available,所以你必须使用 Vec 或等价物。

最后,剩下的问题是:

I thought that a Box is basically just a pointer to somewhere on the heap though so I don't understand why that cannot be cloned?

Box 不仅仅是一个指针,它是一个 owning 指向堆分配对象的指针。如果您只是通过复制底层指针来克隆它,就像您建议的那样,删除克隆和原始框会导致双重释放。要安全地克隆一个 Box,底层对象也必须被克隆,这需要它的类型实现 Clone 当盒子包含一个类型擦除的 dyn Trait 对象时。

通过复制指针实现廉价Clone的Rust智能指针被称为Rc并且是安全的,因为它使用引用计数来确保对象仅在最后一次引用时被删除它消失了。