2

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

4

1 回答 1

4

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

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

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

如果使用into_iter(),则使用原始集合并迭代从中提取的实际值,因此您无需克隆它们。不幸into_iter()的是,它还不能用于数组,所以你必须使用 aVec或等效的。

最后,剩下的问题是:

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

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

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

于 2020-12-05T12:55:34.203 回答