I'm creating a HashMap<u64, Box<dyn MyTrait>>. I can create the HashMap and insert a struct that implements MyTrait, but when I retrieve MyTrait and try to use it, the compiler complains at me:
error[E0161]: cannot move a value of type dyn MyTrait: the size of dyn MyTrait cannot be statically determined
I was under the impression that a trait consists of two pointers, one to the vtable and one to the object data. So the size of any trait, including MyTrait, should be 2 * pointer_size. Furthermore, the object data pointer points to a MyStruct, which is of known size. Clearly I'm wrong in my understanding but I can't figure out why.
Here's my code:
use std::collections::HashMap;
fn main() {
let mut hm: HashMap<u64, Box<dyn MyTrait>> = HashMap::new();
hm.insert(0, Box::new(MyStruct{num: 0}));
match hm.get(&(0 as u64)) {
Some(r) => {
r.my_fun();
}
None => { println!("not found");}
}
}
pub trait MyTrait {
fn my_fun(self);
}
struct MyStruct {
num: u64,
}
impl MyTrait for MyStruct {
fn my_fun(self) {
println!("num is {}", self.num);
return
}
}