rust - 如何构造带盒装 Fn 值的 HashMap

标签 rust hashmap closures

我对 Rust 的使用还比较陌生,我在 Advent of Code 中使用它来帮助我学习。对于第四个问题,我想使用 HashMap 创建一个查找表以从字符串键映射到函数值。我知道 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 基本上只是指向堆上某处的指针,所以我不明白为什么不能克隆它?

最佳答案

构建 HashMap 的正确方法是首先避免克隆:

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

克隆在您的原始代码中是必需的,因为您正在遍历对数组中项目的引用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 不仅仅是一个指针,它是一个指向堆分配对象的拥有指针。如果您只是通过复制底层指针来克隆它,就像您建议的那样,删除克隆和原始框会导致双重释放。要安全地克隆 Box,还必须克隆底层对象,这需要其类型实现 Clonesome additional effort当盒子包含类型删除的 dyn Trait 对象时。

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

关于rust - 如何构造带盒装 Fn 值的 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65157092/

相关文章:

enums - Rust 中逻辑上但非法的未初始化变量

rust - 在结构中的函数指针类型中指定生命周期

rust - 如何从 Rocket 的请求中检索 HTTP header ?

java - 将 guava multi map 值转换为列表

javascript - JavaScript 闭包返回的函数的范围和执行上下文

Haskell 排列库函数 - 请澄清一下?

build - 如何在 Rust 中获取源代码的哈希值

java - Java 中的 HashMap 无法散列 MyObject

java - 黑客排名频率查询

javascript - 通过将函数传递给 setCount 来修复陈旧闭包的副作用