I have two HashMaps and want to swap a value between them under certain conditions. If the key does not exist in the second HashMap, it should be inserted. I do not want to clone the value, since that is too expensive.
But in this example, I just want to take the trait ATrait
out of the HashMap
and move it to another 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));
}
And I got an error
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`
I would appreciate if someone answered my question and explained to me what this error means.