I have Instance struct with HashSet field for storing nonordered numbers with easy removing and adding with duplicates control.
Then there is another struct called Matrix, which holds an two-dimensional array of Instance struct.
I create the new() method in trait for Instance to use in array initialization, but using this method gives error during compilation, saying that HashSet does not implement the Copy trait.
Here is the code:
#![allow(unused)]
use std::collections::HashSet;
struct Instance {
ids: HashSet<u8>,
value: u8,
}
trait IsInstance {
fn new() -> Instance;
}
impl IsInstance for Instance {
fn new() -> Instance {
Instance {
ids: [1, 2, 3, 5].iter().cloned().collect(),
value: 0,
}
}
}
/*
Line below is commented due to error:
error[E0204]: the trait `Copy` may not be implemented for this type
--> src/main.rs:26:6
|
5 | ids: HashSet,
| ---------------- this field does not implement `Copy`
...
26 | impl Copy for Instance {}
| ^^^^
*/
//impl Copy for Instance {}
impl Clone for Instance {
fn clone(&self) -> Instance {
Instance {
ids: self.ids,
value: self.value,
}
}
}
struct Matrix {
instances: [[Instance; 4]; 4],
status: u8,
}
fn main() {
let mut m = Matrix {
instances: [[Instance::new(); 4]; 4],
status: 0,
};
}
Compiling this gives error:
error[E0507]: cannot move out of `self.ids` which is behind a shared reference
--> src/main.rs:42:18
|
42 | ids: self.ids,
| ^^^^^^^^ move occurs because `self.ids` has type `std::collections::HashSet<u8>`, which does not implement the `Copy` trait
error[E0277]: the trait bound `Instance: std::marker::Copy` is not satisfied
--> src/main.rs:60:22
|
60 | instances : [[Instance::new(); 4]; 4],
| ^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `Instance`
|
= note: the `Copy` trait is required because the repeated element will be copied
error[E0277]: the trait bound `[Instance; 4]: std::marker::Copy` is not satisfied
--> src/main.rs:60:21
|
60 | instances : [[Instance::new(); 4]; 4],
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `[Instance; 4]`
|
= note: the `Copy` trait is required because the repeated element will be copied
Is there any way to properly initialize this array? I clearly missed something, but didn't find HashSet copy implementation working with arrays. Maybe there is another way to implement this?