Swapping traits between two hashmaps

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`

playground

I would appreciate if someone answered my question and explained to me what this error means.

HashMap::<K, V>::remove() returns an Option<V>, since there might not be any key-value pair to remove. Why not check the documentation?

When you call remove, you get an Option, which is None if it doesn't contain an item. Additionally, the item was already boxed when you inserted.

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

The error message was that there is no impl ATrait for Option<Box<dyn ATrait>> {}, which is the type you got back from remove.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.