我有两个 HashMap,想在某些条件下交换它们之间的值。如果 key 在第二个 HashMap 中不存在,则应该插入它。我不想克隆这个值,因为那太贵了。
但在这个例子中,我只想取 trait ATrait
出HashMap
并将其移至另一个 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/