I want to have something as follows:
pub trait Domainable: Eq + Hash {}
impl<T: Eq + Hash> Domainable for T {}
pub struct Variable<T: Domainable> {
domain: HashSet<T>,
}
pub struct Assignment<'a, T: Domainable> {
variable: &'a Variable<T>,
assignment: T,
}
pub struct State<'a, T: Domainable> {
assignments: Vec<&'a Assignment<'a, dyn Domainable>>,
}
In effect, I want to have a vector of assignments of possibly different domainable types within the state. For example:
let var1 = Variable::new(HashSet::from([1, 2, 3, 4]));
let var2 = Variable::new(HashSet::from([true, false]));
let assignment1 = Assignment::new(&var1, 2);
let assignment2 = Assignment::new(&var2, false);
let state = State::new(vec![assignment1, assignment2]);
However, it keeps giving errors for dyn Domainable
:
error[E0038]: the trait `Domainable` cannot be made into an object
--> src/main.rs:17:41
|
17 | assignments: Vec<&'a Assignment<'a, dyn Domainable>>,
| ^^^^^^^^^^^^^^ `Domainable` cannot be made into an object
|
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
|
::: src/main.rs:4:11
|
4 | pub trait Domainable: Eq + Hash {}
| ---------- this trait cannot be made into an object...
I have read other posts where they have suggested to use &dyn ThingTrait
similarly for the trait objects, so I am not sure what's wrong with my code.