rust - 在两个 HashMap 之间交换特征

标签 rust

我有两个 HashMap,想在某些条件下交换它们之间的值。如果 key 在第二个 HashMap 中不存在,则应该插入它。我不想克隆这个值,因为那太贵了。

但在这个例子中,我只想取 trait ATraitHashMap并将其移至另一个 HashMap

use std::collections::HashMap;

trait Foo {
    type Bar;
}

struct Analyze<T: Foo> {
    save: T,
}

trait ATrait {}

impl<T: Foo> ATrait for Analyze<T> {}

struct SomeStruct;
impl Foo for SomeStruct {
    type Bar = ();
}

fn main() {
    let mut hm: HashMap<usize, Box<dyn ATrait>> = HashMap::new();
    let mut hm1: HashMap<usize, Box<dyn ATrait>> = HashMap::new();

    hm1.insert(
        1,
        Box::new(Analyze {
            save: SomeStruct {},
        }),
    );

    /*
    --------
    Swapping values between two HashMaps
    --------
    */
    let t1 = hm1.remove(&1);
    hm.insert(1, Box::new(t1));
}

我得到了一个错误

error[E0277]: the trait bound `std::option::Option<std::boxed::Box<dyn ATrait>>: ATrait` is not satisfied
  --> src/main.rs:37:18
   |
37 |     hm.insert(1, Box::new(t1));
   |                  ^^^^^^^^^^^^ the trait `ATrait` is not implemented for `std::option::Option<std::boxed::Box<dyn ATrait>>`
   |
   = note: required for the cast to the object type `dyn ATrait`

playground

如果有人回答我的问题并向我解释此错误的含义,我将不胜感激。

最佳答案

首先,调用 remove 得到的值在 hashmap 上是 Option<V>在哪里 V是存储在 map 中的值的类型,这是有道理的 - 否则如果您要求的值不存在,它将返回什么?

二、HashMap中存储的类型是 Box<dyn ATrait> ,因此无需重新装箱以将其存储在第二个 HashMap .

这会起作用:

let t1 = hm1.remove(&1).unwrap();
hm.insert(1, t1);

但是,只能使用 unwrap如果您完全确定该值将存在并且如果不存在该程序将无法继续。否则使用 match , if let等以适本地处理逻辑。

关于rust - 在两个 HashMap 之间交换特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61991996/

相关文章:

rust - 常量 ìf` 表达式条件下的关联常量

rust - 使用 kcov 时如何从代码覆盖中排除测试函数?

rust - 在Bevy Engine中,如何在for-each系统中使用&mut查询?

rust - 为什么在匹配整数时会出现错误 "expected integral variable, found Option"?

rust - 扩展 Rust 生命周期

rust - 特质 `std::convert::From<cli::Opts>`未实现

string - 在 Rust 中查询结构向量

rust - 为 Enum 实现 PartialEq,以便多个变体相等

rust - 我应该在 FFI 上下文中传递可变引用还是转移变量的所有权?

reference - CString::new().unwrap().as_ptr() 给出空 *const c_char