how can I create a copy of a trait object for local calculations?
The problem is that I want to have a function that takes a mutable reference to a trait object in order to do some calculations and modify it based on those calculations, but during the calculations, the function has to modify the trait object temporarily and locally to do calculations with the modified version of it.
I've tried the following (and variations):
struct Data {
fields: Vec<f32>
}
trait CustomCollection {
fn get_mut(&mut self) -> &mut [f32];
}
impl CustomCollection for Data {
fn get_mut(&mut self) -> &mut [f32] {
return &mut self.fields;
}
}
fn copy(s: &mut dyn CustomCollection) {
let c: Box::<dyn CustomCollection> = Box::new(*s);
}
fn main() {
let mut d = Data{fields: vec![1f32, 2.0, 3.0]};
copy(&mut d);
}
but I get an error:
error[E0277]: the size for values of type `dyn CustomCollection` cannot be known at compilation time
--> src/test.rs:16:51
|
16 | let c: Box::<dyn CustomCollection> = Box::new(*s);
| -------- ^^ doesn't have a size known at compile-time
| |
| required by a bound introduced by this call
|
= help: the trait `Sized` is not implemented for `dyn CustomCollection`
note: required by a bound in `Box::<T>::new`
--> /rustc/fc594f15669680fa70d255faec3ca3fb507c3405/library/alloc/src/boxed.rs:204:6
|
= note: required by this bound in `Box::<T>::new`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.