【问题标题】:How to construct a HashMap with boxed Fn values如何使用装箱的 Fn 值构造 HashMap
【发布时间】:2021-03-17 07:19:37
【问题描述】:

我对使用 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 基本上只是指向堆上某个位置的指针,所以我不明白为什么不能克隆它?

【问题讨论】:

    标签: rust hashmap closures


    【解决方案1】:

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

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

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

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

    最后,剩下的问题是:

    我认为 Box 基本上只是指向堆上某个位置的指针,所以我不明白为什么不能克隆它?

    Box 不仅仅是一个指针,它是一个 拥有 指向堆分配对象的指针。如果您只是按照您的建议通过复制底层指针来克隆它,那么删除克隆和原始框将导致双重释放。为了安全地克隆Box,还必须克隆底层对象,这要求它的类型实现Clonesome additional effort,当盒子包含一个类型擦除的dyn Trait 对象时。

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

    【讨论】:

    • 我从 HashMap 示例文档中复制了我原来的 .iter().cloned() 方法:doc.rust-lang.org/std/collections/struct.HashMap.html#examples,如果他们也可以在那里提及 vec / into_iter() 方法将会很有帮助。
    • @RyanCollingham 这是一个很好的观点,尽管vec![] 方法在一般文档中可能不合适,它必须比 StackOverflow 的答案更严格。文档需要警告使用vec![] 会导致分配,这并不总是可以接受的,并且这样的警告会减损如何构造 HashMap 的主要信息。一旦 #65819 得到解决,该问题就会消失,文档将只使用 [...].into_iter() 而无需克隆或分配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2016-05-22
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2018-02-20
    相关资源
    最近更新 更多